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;
'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.
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
p is a pointer variable. Its value is the address of i. When you call f, you pass the value of p, which is the address of i.
No pass-by-reference in C, but p "refers" to i, and you pass p by value.
Because you're passing a pointer(memory address) to the variable p into the function f. In other words you are passing a pointer not a reference.
You're not passing an int by reference, you're passing a pointer-to-an-int by value. Different syntax, same meaning.