Zurück zu den Links

Pass by Value

In C, function call arguments are passed by value, meaning the actual value of a and b is copied into the function’s stack. Therefore this incorrect version of swap fails to actually modify the values we are working with in main:

#include <stdio.h>

// Swaps a and b.
void swap (int a, int b) {
    int tmp = a;
    a = b;
    b = tmp;
}

int main () {
    int a = 1;
    int b = 2;

    printf("Before: a=%i, b=%i.\n", a, b);
    swap(a, b);
    printf("After: a=%i, b=%i.\n", a, b);

    return 0;
}

By changing swap to work on int pointers instead of ints, we obtain the correct version:

#include <stdio.h>

// Swaps a and b.
void swap (int* a, int* b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int main () {
    int a = 1;
    int b = 2;

    printf("Before: a=%i, b=%i.\n", a, b);
    swap(&a, &b);
    printf("After: a=%i, b=%i.\n", a, b);

    return 0;
}