user2479918
user2479918

Reputation: 23

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){...}

Upvotes: 2

Views: 114

Answers (2)

duselbaer
duselbaer

Reputation: 935

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.

Upvotes: 1

Spook
Spook

Reputation: 25927

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.

Upvotes: 4

Related Questions