Search code examples
c++referencepass-by-reference

Syntax logic behind ++ with respect to references and as a return value


int f3(int i, int j) {
    int& k = i;
    ++j;
    return ++k;
}
int main()
{
    int i = 2, j = 4, k;
    k = f3(i, j);
    cout << "i: " << i << " j: " << j << " k: " << k << endl;
    return 0;
}

why do I get i = 2 and k = 3. I mean surely because I have set int& k = i, both i and k are in essence the same variable as they share the same memory space. Can anyone explain why this is so in simple english? Or what am I not understanding?


Solution

  • Here you set i to 2:

    int i=2,
    

    And here you pass the i:

    k=f3(i,j);
    

    However, you're passing a copy of the i:

    int f3(int i, int j) // you need a "&" in here too if you want to pass the reference
    

    So in this line:

    int& k = i;
    

    You set k to be a reference to the copy of i. Thus when you change it, the actual i from main isn't changed.

    Instead, try this:

    int f3(int &i, int j) { // now you're pssing a reference to i, not a copy thereof
    

    And your output value for i will be 3. For a nice example of call by reference, see here.