If C does not support passing a variable by reference, why does this work?
#include <stdio.h>
void f(int *j) {
(*j)++;
}
int main() {
int i = 20;
int *p = &i;
f(p);
printf("i = %d\n", i);
return 0;
}
Output
$ gcc -std=c99 test.c $ a.exe i = 21
You're not passing an int by reference, you're passing a pointer-to-an-int by value. Different syntax, same meaning.
In C, to pass by reference you use the address-of operator
&
which should be used against a variable, but in your case, since you have used the pointer variablep
, you do not need to prefix it with the address-of operator. It would have been true if you used&i
as the parameter:f(&i)
.You can also add this, to dereference
p
and see how that value matchesi
:'Pass by reference' (by using pointers) has been in C from the beginning. Why do you think it's not?
In C everything is pass-by-value. The use of pointers gives us the illusion that we are passing by reference because the value of the variable changes. However, if you were to print out the address of the pointer variable, you will see that it doesn't get affected. A copy of the value of the address is passed-in to the function. Below is a snippet illustrating that.
Source: www-cs-students.stanford.edu