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)开发者_如何学C;
return 0;
}
Output:
$ gcc -std=c99 test.c
$ a.exe
i = 21
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
Illusion of pass-by-reference
We change the piece of code slightly. param
is a pointer now.
#include <stdio.h>
void function2(int *param) {
printf("I've received value %d\n", *param);
(*param)++;
}
int main(void) {
int variable = 111;
function2(&variable);
printf("variable %d\n", variable);
return 0;
}
The result is
I've received value 111
variable=112
That makes you believe that the parameter was passed by reference. It was not. It was passed by value, the param value being an address. The int type value was incremented, and that is the side effect that make us think that it was a pass-by-reference function call.
Pointers - passed-by-value
How can we show/prove that fact? Well, maybe we can try the first example of Scalar variables, but instead of scalar we use addresses (pointers). Let's see if that can help.
#include <stdio.h>
void function2(int *param) {
printf("address param is pointing to %d\n", param);
param = NULL;
}
int main(void) {
int variable = 111;
int *ptr = &variable;
function2(ptr);
printf("address ptr is pointing to %d\n", ptr);
return 0;
}
The result will be that the two addresses are equal (don't worry about the exact value).
Example result:
address param is pointing to -1846583468
address ptr is pointing to -1846583468
In my opinion this proves clearly that pointers are passed-by-value. Otherwise ptr
would be NULL
after function invocation.
In C, Pass-by-reference is simulated by passing the address of a variable (a pointer) and dereferencing that address within the function to read or write the actual variable. This will be referred to as "C style pass-by-reference."
Source: www-cs-students.stanford.edu
Because there is no pass-by-reference in the above code. Using pointers (such as void func(int* p)
) is pass-by-address.
This is pass-by-reference in C++ (won't work in C):
void func(int& ref) {ref = 4;}
...
int a;
func(a);
// a is 4 now
Your example works because you are passing the address of your variable to a function that manipulates its value with the dereference operator.
While C does not support reference data types, you can still simulate passing-by-reference by explicitly passing pointer values, as in your example.
The C++ reference data type is less powerful but considered safer than the pointer type inherited from C. This would be your example, adapted to use C++ references:
void f(int &j) {
j++;
}
int main() {
int i = 20;
f(i);
printf("i = %d\n", i);
return 0;
}
You're passing a pointer(address location) by value.
It's like saying "here's the place with the data I want you to update."
No pass-by-reference in C, but p "refers" to i, and you pass p by value.
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.
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
Short answer: Yes, C does implement parameter passing by reference using pointers.
While implementing parameter passing, designers of programming languages use three different strategies (or semantic models): transfer data to the subprogram, receive data from the subprogram, or do both. These models are commonly known as in mode, out mode, and inout mode, correspondingly.
Several models have been devised by language designers to implement these three elementary parameter passing strategies:
Pass-by-Value (in mode semantics) Pass-by-Result (out mode semantics) Pass-by-Value-Result (inout mode semantics) Pass-by-Reference (inout mode semantics) Pass-by-Name (inout mode semantics)
Pass-by-reference is the second technique for inout-mode parameter passing. Instead of copying data back and forth between the main routine and the subprogram, the runtime system sends a direct access path to the data for the subprogram. In this strategy the subprogram has direct access to the data effectively sharing the data with the main routine. The main advantage with this technique is that its absolutely efficient in time and space because there is no need to duplicate space and there is no data copying operations.
Parameter passing implementation in C: C implements pass-by-value and also pass-by-reference (inout mode) semantics using pointers as parameters. The pointer is send to the subprogram and no actual data is copied at all. However, because a pointer is an access path to the data of the main routine, the subprogram may change the data in the main routine. C adopted this method from ALGOL68.
Parameter passing implementation in C++: C++ also implements pass-by-reference (inout mode) semantics using pointers and also using a special kind of pointer, called reference type. Reference type pointers are implicitly dereferenced inside the subprogram but their semantics are also pass-by-reference.
So the key concept here is that pass-by-reference implements an access path to the data instead of copying the data into the subprogram. Data access paths can be explicitly dereferenced pointers or auto dereferenced pointers (reference type).
For more info please refer to the book Concepts of Programming Languages by Robert Sebesta, 10th Ed., Chapter 9.
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 variable p
, 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 matches i
:
printf("p=%d \n",*p);
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.
What you are doing is pass by value not pass by reference. Because you are sending the value of a variable 'p' to the function 'f' (in main as f(p);)
The same program in C with pass by reference will look like,(!!!this program gives 2 errors as pass by reference is not supported in C)
#include <stdio.h>
void f(int &j) { //j is reference variable to i same as int &j = i
j++;
}
int main() {
int i = 20;
f(i);
printf("i = %d\n", i);
return 0;
}
Output:-
3:12: error: expected ';', ',' or ')' before '&' token void f(int &j); ^ 9:3: warning: implicit declaration of function 'f' f(a); ^
pointers and references are two different thigngs.
A couple of things I have not seen mentioned.
A pointer is the address of something. A pointer can be stored and copied like any other variable. It thus have a size.
A reference should be seen as an ALIAS of something. It does not have a size and cannot be stored. It MUST reference something, ie. it cannot be null or changed. Well, sometimes the compiler needs to store the reference as a pointer, but that is an implementation detail.
With references you don't have the issues with pointers, like ownership handling, null checking, de-referencing on use.
I think C in fact supports pass by reference.
Most languages require syntactic sugar to pass by reference instead of value. (C++ for example requires & in the parameter declaration).
C also requires syntactic sugar for this. It's * in the parameter type declaration and & on the argument. So * and & is the C syntax for pass by reference.
One could now argue that real pass by reference should only require syntax on the parameter declaration, not on the argument side.
But now comes C# which does support by reference passing and requires syntactic sugar on both parameter and argument sides.
The argument that C has no by-ref passing cause the the syntactic elements to express it exhibit the underlying technical implementation is not an argument at all, as this applies more or less to all implementations.
The only remaining argument is that passing by ref in C is not a monolithic feature but combines two existing features. (Take ref of argument by &, expect ref to type by *.) C# for example does require two syntactic elements, but they can't be used without each other.
This is obviously a dangerous argument, cause lots of other features in languages are composed of other features. (like string support in C++)
That code fragment (with tiny modification)
void add_number(int * const a) {
*a = *a + 2;
}
also exists in C++ and is semantically equivalent to
void add_number(int &a) {
a = a + 2;
}
The compiler is expected to generate equal binary code of the function add_number
in both cases. Now, when you consider an integer to be a value, that value is passed by it's reference, where in the upper pattern the reference appears technically as pointer.
Conclusion
C supports the semantics of passing an instance by reference.
Even technically with int *a
you pass *a
, which is a reference.
Calling a pointer a reference (as Java and Javascript do) is a completely different use of the word reference than in pass-by-reference. C does not support pass-by-reference. Here is your example re-written to show that it not really passing a value by reference, only a pointer by value.
#include <stdio.h>
void f(int *j) {
int k = (*j) + 1;
j = &k;
}
int main() {
int i = 20;
int *p = &i;
f(p);
printf("i = %d\n", i);
printf("j = %d\n", *p);
printf("i(ptr) = %p\n", &i);
printf("j(ptr) = %p\n", p);
return 0;
}
Here is the output
i = 20
j = 20
i(ptr) = 0x7ffdfddeee1c
j(ptr) = 0x7ffdfddeee1c
As you can see, the value stays the same, but more importantly the pointers don't change either. However, C++ allows pass by reference. Here is the same example put through a C++ compiler but with and added ampersand in the header which makes this a reference parameter.
#include <stdio.h>
void f(int *&j) { // note the & makes this a reference parameter.
// can't be done in C
int k = (*j) + 1;
j = &k;
}
int main() {
int i = 20;
int *p = &i;
f(p);
printf("i = %d\n", i);
printf("j = %d\n", *p);
printf("i(ptr) = %p\n", &i);
printf("j(ptr) = %p\n", p);
return 0;
}
Here is the output
i = 20
j = 21
i(ptr) = 0x7ffcb8fc13fc
j(ptr) = 0x7ffcb8fc13d4
Note that we were able to change the actual pointer!
Just as a reference The Dragon Book is a classic Computer Science text book on compilers. Because it's the most popular compiler book ever (or at least it was when I was in college, maybe I'm wrong), I would guess that the vast, vast majority of people who design languages or write compilers leaned from this book. Chapter 1 of this book explains these concepts very clearly and explains why C is pass-by-value only.
'Pass by reference' (by using pointers) has been in C from the beginning. Why do you think it's not?
精彩评论