1

Assume we have this piece of code:

#include <iostream>

int foo(int &x, int& y)
{
   return x * y;
}

int main()
{
   int x = 10;
   int y = 5;

   std::cout << foo(++x, x+=y);
}

Could you please explain why this expression gives output 256? Which is the exact order of parameters-assignment, or it is compiler-defined.Even if we consider both cases of evaluation order of parameters if first case(when x++ evaluated before x+=y) the logical output should be 176, in second case 240. I really do not understand the logic of resulted output.

xskxzr
  • 12,442
  • 12
  • 37
  • 77

3 Answers3

1

what you are doing is:-

foo(++x, x+=y);

let's break this x = 10; y = 5;

now ++x, here ++ is preincrement operator, which means that first x will be incremented and then used.on the other hand x++ means that first x will be used then it will get incremented.So what happens here is

++x   // turns x = 11 and then
x+=y  // turns x = 16 , which also changes first parameter to x to 16 

in short what you are sending to function is

foo(16,16)

16*16 = 256

learn this topics:- unary and binary operators and preincrement and postincrement

J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
0

int &x and int &y those become the reference to evaluated x from the function call. x = 16 before the function call.

Other words, this is what you do (the order of evaluating arguments is not guaranteed):

int main()
{
   int x = 10;
   int y = 5;
   ++x;
   x+=y; // => x 

   std::cout << foo(x, x); 
}
XoRdi
  • 1
  • 3
  • I my point of view the references are not the reason of the output. Pass-by-value parameters will give the same output as well, but you are right, before function call there are two x with value 16. Thanks for response. –  Sep 08 '18 at 07:24
  • @Swordfish Yes I know that the order is not guaranteed, however we make the addition operations, so in that case we can skip the evaluation order (only in that case). But we know that (x) both expressions will be evaluated before function call, and they evaluate to x after operations. – XoRdi Sep 08 '18 at 07:47
-2

int& x = y; is setting x's ADDRESS to y's ADDRESS (x is a reference to y)


so what is happening here is that int x=10; and int y=5; .When you are passing the arguments to the function, for ++x x's value becomes x=11 and for x+=y(which means x=x+y) the value of x changes from x=11 to x=11+5 that is x=16. now we have both the arguments as 16 that is :

int foo(16, 16) { return 16 * 16; }

so 16*16 is 256. This is the output;


actually reference has nothing to do in this program.(if i am wrong then please correct me)