Lesson 23 / 38
Pointers & Functions
Pass addresses to functions so they can modify the caller's variables, as in a swap function.
C is always pass-by-value
Function arguments are always copied. To let a function change a caller's variable, pass a pointer to it instead of the value itself — this is how C simulates "pass by reference".
swap with pointers
Passing &a and &b lets swap reach into the caller's memory directly.
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main(void) {
int a = 1, b = 2;
swap(&a, &b);
printf("%d %d\n", a, b);
return 0;
}
Output:
2 1
Quick check: Why does `swap(int x, int y)` (no pointers) fail to swap the caller's variables?
- C doesn't allow swapping
- The compiler optimizes it away
- Pointers cannot be passed
- x and y are copies of the originals
Answer
x and y are copies of the originals — Without pointers, the function only swaps its own local copies.