r/CodingHelp • u/RunTimeTerroR69 • Apr 07 '21
[C++] Where am i going wrong ? plz help
int a = 1;
a = ++a + ++a + ++a;
cout <<a;
what should be the output ? i tried it on paper i got the answer as 9 but on compiling & running the code its showing me the answer as 10 , can anyone help ?
16
7
u/jedwardsol Professional Coder Apr 07 '21
The behaviour is undefined. There is no right answer.
-1
u/Boris-Holo Apr 07 '21
this is definitely not undefined behavior
5
u/jedwardsol Professional Coder Apr 07 '21
2
2
1
u/NoAd7524 Apr 08 '21 edited Apr 08 '21
Tried it with 5 different compilers and answer given is always 10. It's probably due to how compiler logic handles the expression. It seems for this case initial value of 1 is increased becoming 2, and increased becoming 3, and then increased becoming 4. Maybe those three values are stacked. Then 2+3+4 = 9 and then that 9 PLUS ONE yields 10 for the end result. If initially a=0 a similar thing happens. The 0 is increased becoming 1, then 2 and then 3. Those three values are added yielding 1+2+3=6. Then that 6 PLUS ONE results in 7 for the answer. I tried it for values 3, 4 and 5 and got the same behavior-based result.
1
u/jedwardsol Professional Coder Apr 08 '21 edited Apr 08 '21
https://godbolt.org/z/66eq7q4Te
Gcc says 10.
Clang and ICC say 9
MSVC says 12
They're all correct. Or, at least, all not wrong.
1
u/NoAd7524 Apr 08 '21
These differences probably due to the way each of those chose to process expressions internally.
1
u/jedwardsol Professional Coder Apr 08 '21
Right.
I am not sure if we are arguing or agreeing with each other.
5 compilers agreeing on 10, and 2 others saying 9 and 12 isn't evidence that 10 is right. Or that 10 is better.
All answers, or something else entirely, are acceptable outcomes from that code.
1
u/NoAd7524 Apr 08 '21
I'm not agreeing nor arguing with you or with anyone here. I just posted what I observed. Thank you for your input. It is very interesting to see how these compilers behave.
3
u/[deleted] Apr 07 '21
you cannot really increment like that it you need to add some parenthesis a = ((++a) + (++a) + (++a)) or just write a for loop that increments for(int a = 0; a < 3; a++){ cout << a; } hope this helps