I am confused about the meaning of "pass by reference" in C and C++.
In C, there are no references. So I guess pass by reference means passing a pointer. But then why not call it pass by pointer?
In C++, we have both pointers and references (and stuff like iterators that lies close). So what does pass by reference mean here?
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.
"Passing by value" means that you pass the actual value of the variable into the function. So, in your example, it would pass the value 9. "Passing by reference" means that you pass the variable itself into the function (not just the value). So, in your example, it would pass an integer object with the value of 9.
The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C programming uses call by value to pass arguments.
In colloquial usage, "pass by reference" means that, if the callee modifies its arguments, it affects the caller, because the argument as seen by the callee refers to the value as seen by the caller.
The phrase is used independent of the actual programming language, and how it calls things (pointers, references, whatever).
In C++, call-by-reference can be done with references or pointers. In C, call-by-reference can only be achieved by passing a pointer.
"Call by value":
void foo( int x )
{
// x is a *copy* of whatever argument foo() was called with
x = 42;
}
int main()
{
int a = 0;
foo( a );
// at this point, a == 0
}
"Call by reference", C style:
void foo( int * x )
{
// x is still a *copy* of foo()'s argument, but that copy *refers* to
// the value as seen by the caller
*x = 42;
}
int main()
{
int a = 0;
foo( &a );
// at this point, a == 42
}
So, strictly speaking, there is no pass-by-reference in C. You either pass the variable by-value, or you pass a pointer to that variable by-value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With