1
#include <iostream>
using namespace std;

void f(int& p)
{
    p += 2;
}

int main()
{
    int x = 10;
    f(x);
    int y = x + 1;
    f(y);
    cout << "x is " << x << endl;
    cout << "y is " << y << endl;
    system("PAUSE");
    return 0;
}

Now the answer is that x is 12 and y is 15.

I kind of understand maybe that x is 12. To explain if I got it right is that as

void f (int &p)
{
    p += 2;
}

and as int x = 10 so you 10 += 2 which is 12 so x is 12.

But I don't quite understand why y is 15.

Is it because I use 12 as x for int y = x + 1 so it's 12 + 1 which is 13 and then 13 += 2 which is 15?

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
Nina555
  • 15
  • 6

2 Answers2

0

Is it because I use 12 as x for int y = x + 1 so it's 12 + 1 which is 13 and then 13 += 2 which is 15?

Yes. f is a function that takes an integer value by reference and increments it by 2. After the function call, the integer will be permanently changed.

int x = 10;
// `x` is 10.

f(x);
// `x` is now 12.

int y = x + 1;
// `y` is 13.

f(y);
// `y` is now 15.
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
0

The values are changed inside f(), because they are sent by reference - void f(int& p).

So:

int x = 10;
f(x);  // x is 12 after the call
int y = x + 1; // y = 13
f(y);  // y = (12+1) + 2 = 15 after the call

Updated question:

Is it because I use 12 as x for int y = x + 1 so it's 12 + 1 which is 13 and then 13 += 2 which is 15?

Yes, see above.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46