The illusion of pass-by-reference in C

Farrat Code
2 min readApr 5, 2021

First of all everything in C is passed by value and I will show you how, let’s started.

Look at the code below:

void addone(int n) {
n++; // therefore incrementing it has no effect
}
int main(){
int n;
printf("Before: %d\n", n);
addone(n);
printf("After: %d\n", n);
}

So, of course, you guess the answer it is the same value of n before and after passing it through the function and that because of that n is local variable which only exists within the function scope therefore incrementing it has no effect.

Now take a look at the code below and tell me the difference :

void addone(int *n) {
(*n)++; // this will effectively increment the value of n
}
int main(){
int n;
printf("Before: %d\n", n);
addone(&n);
printf("After: %d\n", n);
}

The result will be n and n+1; You may be thinking that we are passing it by reference, but No, take a step back …… yeah you get it we pass the address of n by value for the function addone so what happened? n is a pointer here which point to a memory-adress outside the function scope this will effectively increment the value of n.

Do you want proof here it is :

void function2(int *n) {
printf("param's address %d\n", n);
n= NULL;
}

int main(void) {
int n = 111;
int *ptr = &n;

function2(n);
printf("ptr's address %d\n", n);
return 0;
}

What you think the result will be NULL!!……… No, The result will be that the two addresses are equal.

n's address -98358848478
ptr's address -98358848478

this proves clearly that pointers are passed-by-value. Otherwise ptr would be NULL after function invocation.

--

--