Passing by Reference in C
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; Int *P = &I; F(P)...
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
19 Answers
Because you're passing the value of the pointer to the method and then dereferencing it to get the integer that is pointed to.
That is not pass-by-reference, that is pass-by-value as others stated.
The C language is pass-by-value without exception. Passing a pointer as a parameter does not mean pass-by-reference.
The rule is the following:
A function is not able to change the actual parameters value.
(The above citation is actually from the book K&R)
Let's try to see the differences between scalar and pointer parameters of a function.
Scalar variables
This short program shows pass-by-value using a scalar variable. param is called the formal parameter and variable at function invocation is called actual parameter. Note incrementing param in the function does not change variable.
#include <stdio.h>
void function(int param) {
printf("I've received value %d\n", param);
param++;
}
int main(void) {
int variable = 111;
function(variable);
printf("variable %d\m", variable);
return 0;
}
The result is
I've received value 111
variable=111