If C does not support passing a variable by reference, why does this work?
#include
void f(int *j) {
(*j)++;
}
int main() {
int i = 20;
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.
void add_number(int *a) {
*a = *a + 2;
}
int main(int argc, char *argv[]) {
int a = 2;
printf("before pass by reference, a == %i\n", a);
add_number(&a);
printf("after pass by reference, a == %i\n", a);
printf("before pass by reference, a == %p\n", &a);
add_number(&a);
printf("after pass by reference, a == %p\n", &a);
}
before pass by reference, a == 2
after pass by reference, a == 4
before pass by reference, a == 0x7fff5cf417ec
after pass by reference, a == 0x7fff5cf417ec