Sub topic 4
Pass by Value and Pass by Pointer
Prerequisites: basic C syntax, functions, addresses, dereferencing, and pointer declarations. You should already know that &x produces the address of x, while *p accesses the object stored at the address in p.
C passes every argument by value
When a function is called, C copies each argument into a parameter. The function can change its local copy, but that change does not affect the original variable.
#include <stdio.h>
void change(int x) {
x = 99;
}
int main(void) {
int a = 10;
change(a);
printf("%d\n", a);
return 0;
}The program prints 10. The parameter x receives a copy of a. Assigning 99 to x changes only that copy.
A pointer argument is also passed by value. The difference is that the copied pointer still contains the address of the caller's object. Dereferencing it allows the function to modify that object.
#include <stdio.h>
void change(int *p) {
*p = 99;
}
int main(void) {
int a = 10;
change(&a);
printf("%d\n", a);
return 0;
}Here, &a is passed by value into p. Both p and &a point to the same int, so *p = 99 changes a.
Swapping caller variables
A common use of pointer parameters is an in-place operation, meaning the function changes data owned by its caller.
#include <stdio.h>
void swap(int *x, int *y) {
int temporary = *x;
*x = *y;
*y = temporary;
}
int main(void) {
int a = 1;
int b = 2;
swap(&a, &b);
printf("%d %d\n", a, b);
return 0;
}The output is 2 1. The function receives copies of the two addresses, but those addresses identify a and b.
A function can also change where its local pointer points, but that change is not visible to the caller because the pointer itself was copied. To change the caller's pointer, pass a pointer to that pointer, such as int **.
GATE-style reasoning
For each pointer parameter, track two separate facts:
- The parameter variable is local and copied.
- The object reached after dereferencing may be shared with the caller.
Exercise
What does this print, and why? void f(int *p) { p = NULL; } followed by int x = 4; int *q = &x; f(q); printf("%d\n", *q);
Show answer
It prints 4. The function changes only its local copy of q; the caller's pointer still points to x.