Sub topic 4
Pass by value and pass by pointer
What you need first
This chapter assumes you can declare a pointer, take an address with &, and dereference with *. It also assumes you know how a function call receives arguments. Pointer basics are covered in the previous chapter. The call stack gets its own chapter later, so here we only use the idea that each call has its own set of local variables.
The one rule: C passes by value
Every argument in C is copied into the matching parameter when the function is called. The function works on the copy. Nothing the function does to the parameter itself can change the caller's variable.
#include <stdio.h>
void inc(int n) {
n++;
}
void inc_p(int *n) {
(*n)++;
}
int main(void) {
int a = 5;
inc(a);
printf("%d\n", a);
inc_p(&a);
printf("%d\n", a);
return 0;
}This prints 5 and then 6. In inc, the parameter n is a separate int holding a copy of 5, and incrementing it changes only that copy. In inc_p, the copied value is an address. The copy of the address still points at a, so (*n)++ changes the caller's variable.
C has no true pass by reference. Passing a pointer simulates it. You pass the address by value, and the callee uses that address to reach the original object.
The classic swap
#include <stdio.h>
void swap(int *x, int *y) {
int t = *x;
*x = *y;
*y = t;
}
int main(void) {
int a = 1, b = 2;
swap(&a, &b);
printf("%d %d\n", a, b);
return 0;
}The output is 2 1. A version that takes int x, int y would swap only its own copies and leave a and b unchanged.
What the callee receives
| Argument passed | Parameter holds | Can the callee change the caller's object? |
|---|---|---|
| `a` (an int) | Copy of the value | No |
| `&a` | Copy of the address | Yes, through `*p` |
| `p` (a pointer) | Copy of the pointer | Yes for `*p`. No for `p` itself |
| `arr` (an array) | Pointer to the first element | Yes, the elements |
| `s` (a struct) | Copy of the whole struct | No |
The array row follows from array decay, which a later chapter covers in detail. For now, remember that an array parameter such as int arr[] is really int *arr.
Common errors
Changing the pointer, not the pointee
A pointer parameter is itself a local copy. Assigning to it changes only that copy.
#include <stdio.h>
void retarget(int *p, int *q) {
p = q;
*p = 99;
}
int main(void) {
int a = 1, b = 2;
int *p = &a;
retarget(p, &b);
printf("%d %d %d\n", a, b, *p);
return 0;
}The output is 1 99 1. Inside retarget, p = q moves the local p to b, and *p = 99 then writes to b. The p in main still points at a. To change where the caller's pointer points, you must pass its address, which means a pointer to a pointer. A later chapter covers that.
Forgetting the address
Writing swap(a, b) where swap expects int * passes integers where pointers are expected. A compiler reports this as an error or a warning, depending on the compiler and settings. The same mistake with scanf("%d", n) instead of scanf("%d", &n) compiles in many setups. It then crashes or corrupts memory at run time, because scanf treats the value of n as an address.
Returning the address of a local variable
Local variables live only while their function runs. After the function returns, the memory is reused.
int *bad(void) {
int x = 5;
return &x;
}The returned pointer is dangling. Using it is undefined behavior. Common fixes are to let the caller supply the storage, to use static storage, or to allocate on the heap. The simplest is to let the caller supply it:
#include <stdio.h>
void good(int *out) {
*out = 5;
}
int main(void) {
int v;
good(&v);
printf("%d\n", v);
return 0;
}Aliasing in swap
The three-step temp-variable swap works even if both pointers refer to the same object. The XOR swap trick does not.
#include <stdio.h>
void xor_swap(int *x, int *y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
int main(void) {
int a = 5;
xor_swap(&a, &a);
printf("%d\n", a);
return 0;
}This prints 0. The first line computes a ^ a, which is 0, and the value is lost. GATE questions sometimes call a swap-like function with the same address twice.
Structs are copied whole
Passing a struct by value copies every member, including any array inside it. The callee's changes do not reach the caller. For large structs, pass a pointer, and add const if the function should only read. A pointer parameter of type const int * makes the compiler reject writes through it.
Tracing technique for GATE
- Draw one box per variable in each function, and label each box with its function name.
- For each call, write down the value placed in each parameter. For
&a, write the address as an arrow toa's box. - Follow
*pby walking the arrow. Treatp = ...as moving the arrow in the local box only. - When the call returns, erase the callee's boxes. Only changes made through arrows into the caller's boxes survive.
Practice
The program for the first exercise is:
#include <stdio.h>
void f(int *p, int n) {
*p = *p + n;
n = 0;
}
int main(void) {
int a = 3, n = 4;
f(&a, n);
f(&a, n);
printf("%d %d\n", a, n);
return 0;
}Exercise
What does the program above print?
Show answer
It prints "11 4". Each call adds the copied value 4 to a through the pointer, so a goes from 3 to 7 to 11. The assignment n = 0 changes only the parameter copy, so n in main stays 4.
Exercise
A function void set(int *p) contains the statement p = NULL; and main calls set(&x). Does x change, and does anything in main change?
Show answer
Nothing changes. p is a local copy of the address of x, so assigning NULL changes only that copy. The variable x keeps its value, and no pointer in main is affected.