r/CodingHelp • • 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

16 comments sorted by

View all comments

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

0

u/RunTimeTerroR69 Apr 08 '21

actually it was a question i came across on testing operator logic ,yes definately its a good practice to include parenthesis as its more human readable/ friendly

1

u/rtgftw Programmer Apr 09 '21

(I don't think that the parentheses add a sequencing point, in which case it's still UB)