Lesson 22 / 36
Pointers & Functions
Pass a variable's address so a function can modify the original.
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?
- x and y are copies of the originals
- C doesn't allow swapping
- The compiler optimizes it away
Answer
x and y are copies of the originals — Without pointers, the function only swaps its own local copies.