Hii, Here, i’m having a problem in c++ increment.
here is the problem
a = 10;
cout<<(a++ + ++a + a++);
but when i’m running it on java or online cpp compiler, it says output = 34 , but here in clion, it says 33.
I need help to fix it out!
This is an undefined behavior in C++, there are different operation orders and results according to different compiler versions.
You don’t need to tangle with these things, just remember to bracket when you are hesitant in your code.
Then what should be the answer? 33 or 34
You should understand the meaning of undefined behavior. that is, there is no so-called correct answer, and then don’t make such a mistake when coding.
Standard definition says that ++a is Pre-increment and a++ is Post-Increment according to this definition .
cout << (a++ + ++a + a++);
will be evaluated like this:-
cout << (10 + 12 +12);
Hence the answer 34 is the right answer.
This is the Standard definition .
@cultofshubham, Your answer is correct as per standards, but here, in my case, I’m assuming that the compiler first compute prefix statement i.e. ++a, then execute the statement i.e. cout<<(a++ + ++a + a++), then postfix expression i.e. ++a, that’s why I’m getting 33 as after prefix update, value of A will be 11 and then printing 11+ 11+ 11 = 33;
To support my assumption, I’ve tried to print cout<<(a++ + ++a + a++ + a++ + a++);
here I’m getting output 55.
This is not trivial as Java(where these type of prefix/postfix start from left to right) (–>)
but in CPP, it start executing the prefix/postfix increments from right to left (<–)
So, finally, if in a interview it is asked to find the output, then what should we say?
Well, Yes it is language dependent!
Only One this I will suggest change your compiler.
@anon29223724, I have attached the output screenshot, I’m getting ans :33 , so I’m trying to make some assumption that why I’m getting this. Please refer to the screenshot if you haven’t.