0

Can anyone explain how the output is 9?

int a=8; int x=4; int y=++x+(a%x*a/x); cout <<y;

11th Apr 2017, 3:44 PM
Çhandra_Şhekar
Çhandra_Şhekar - avatar
4 Respuestas
+ 11
i.e. The prefix increment comes before everything else.
11th Apr 2017, 4:00 PM
Hatsy Rei
Hatsy Rei - avatar
+ 6
y = (5) + ( 8 % 5 * 8 / 5) remember ++x increments it before its used. so x is now 5. it is also 5 the next two times it is used. also remember modulus and multiplication and division are done left to right so.... y = 5 + (3 * 8 / 5) y = 5 + (24/5) y = 5 + 4 = 9
11th Apr 2017, 3:52 PM
Edward
+ 2
Isn't this a case of undefined behaviour and the outcome depends on the compiler used? That would make the other answers dangerous half wisdom. Check out this link: http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points especially rule 2 under "What is the relation between Undefined Behaviour and Sequence Points?"
11th Apr 2017, 4:31 PM
Tob
Tob - avatar
0
@Edward thank you
11th Apr 2017, 3:55 PM
Çhandra_Şhekar
Çhandra_Şhekar - avatar