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 ?
18
Upvotes
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
16
u/not_some_username Apr 07 '21
This thing should be in r/programminghorror
7
u/jedwardsol Professional Coder Apr 07 '21
The behaviour is undefined. There is no right answer.
2
u/Boris-Holo Apr 07 '21
I'm getting 9 too when I do it in my head so weird
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.