简体   繁体   中英

When we pass by reference, why do we put a variable instead of address(pointer), when calling the function?

void ChangeValueByReference(int &x)
{
    x = 0;
}

int main()
{
    int a = 1;
    ChangeValueByReference(a);
    cout << a;
}

Why don't we put ChangeValueByReference(&a); when calling that function in main()?

Because while defining the function, we said that we will be passing a pointer void ChangeValueByReference(int &x){...}

That's because the ampersand has two different meanings, when used in different places (declaration / statement).

void MyFn(Type & a);

Here & serves as "a reference to" modifier.

Type * pA = &a;

Here & serves as "get a pointer of" operator. Notice that if you have variable a of type Type , &a returns Type * (a pointer to Type ).

Compiler automatically gets a reference to variable, when you pass it to the function. So you can simply call:

ChangeValueByReference(someVariable);

And compiler will know, that it has to get a reference to someVariable.

We did not say that we'll be passing a pointer. We said that we will give a reference. A reference to a variable might internally be handled like a pointer but it is no pointer. A pointer can be 0 - a reference not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM