x++ * ++x?

Hi, may I know why is y= 35 instead of 36???

int x=5,y;
y=x++*++x;
cout<<y // Output: 35
Because your program is ill-formed, its behavior is undefined. The result could be anything.

The problem is, you're modifying x more than once within one sequence point.
Please read https://stackoverflow.com/a/4176333/8690169 for more details

In simpler terms: Do not use a variable that is modified on the same line more than once. This makes your program invalid.

Possible alternative:
1
2
3
int x = 5, y;
y = (x + 1) * (x + 1); // or something like that, depending if you want 36 or 35.
x += 2;
Last edited on
This is undefined behaviour.
If a side effect on a scalar object is unsequenced relative to another side effect on the same scalar object, the behavior is undefined. http://en.cppreference.com/w/cpp/language/eval_order

Topic archived. No new replies allowed.