Inconsistency in passing by reference - how does this simple example of passing by reference work?

StackOverflow https://stackoverflow.com/questions/22739018

  •  23-06-2023
  •  | 
  •  

Pregunta

I had a simple question and was hoping for the underlying logic behind passing by reference.

Here's one code (let's call it Code1):

void fn(int& a)
{
    a = 6;
}

int main()
{
    int b = 5;
    fn(b);
    cout << b;
}

Here's another code (Code2):

void fn(int* ptr)
{
    *ptr = 6;
}

int main()
{
    int b = 5;
    fn(&b);
    cout << b;
}

And a pass by value code (Code 3):

void fn(int a)
{
    a = 6;
}

int main()
{
    int b = 5;
    fn(b);
    cout << b;
}

Here goes my question. Intuitively, I see that while passing by value (Code3), the values are copied ie a would just have taken/copied into itself the value of b. Thus, as a general rule, I see that value passed is just copied always to the called function (here fn). Even with the pointer code (ie Code2), the first line of Code 2 ensures that int *ptr = &a;

I don't understand how this would work in Code1. Saying that &a = b makes no sense. Is this an exception, or does this fit into a rule that is consistent with the cases discussed in the paragraph above?

Thanks!

¿Fue útil?

Solución

In this function:

void fn(int &a) {
a=6;
}

the term "&a" does not mean "the address of the variable a". It means "a reference called a". Code 1 and Code 2 are effectively the same (but note that the function in Code 2 can be passed an invalid pointer, which is (almost) impossible for Code 1).

Otros consejos

For most intents and purposes, a reference is just a pointer in disguise. Different syntax, same effect (mostly).

Conceptually, in your first case what happens is that the same variable has two labels: b, visible within the scope of main(); and a, visible within the scope of fn.

You don't have to worry about what the compiler does "behind the scenes" to implement this concept.

If you mentally promote the compiler's "behind the scenes" actions to actually being imagined principles of C++, e.g. "the reference is a pointer in disguise", then it leads you to get confused about what is actually a pretty simple concept: the ability to give multiple names to a variable.

It is nothing special being a function parameter; e.g. you could write in main():

int a;
int &c = a;

which is exactly equivalent to:

int c;
int &a = c;

In both cases there is an int variable with two labels, a and c.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top