Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of pass by reference in C and C++?

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?

like image 242
Registered User Avatar asked May 10 '16 10:05

Registered User


People also ask

What does pass by reference means?

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.

What is pass by reference and pass by value in C?

"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.

Why is C pass by value?

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.


1 Answers

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.

like image 74
DevSolar Avatar answered Oct 14 '22 09:10

DevSolar