+ 2

what is output ? And why?

int i=5; i= ++i + ++i; cout<<i;

16th Dec 2016, 9:58 AM
vipul chandra
vipul chandra - avatar
4 Answers
+ 3
@Manikanta, Vipul I am sorry to bring bad news and I know that you have probably tested this in the Code Playground (which gives 14 for C++), but the answer is that this really is undefined. To demonstrate, try this in the Java personality of the Code Playground: public class Program { public static void main(String[] args) { int i = 5; i = ++i + ++i; System.out.println(i); } } You can see this is identical to the C++ code but you will see the result is now 13. So which is right? I can also give you the steps of how Java arrives at the 13 result, but it is pointless since it (just as your explanation) relies on stating that the way Java (or C++) did it is the "right way" when, in fact, it is undefined. So, neither 14 or 13 is right or wrong. Both results are undefined i.e. we cannot say which is the right answer. BTW, I also checked on the D compiler (DMD version). It also gave 13 as the result. But that proves nothing.
16th Dec 2016, 1:26 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
+ 1
IIRC that is actually undefined according to the C++ spec. But I couldn't remember why so I looked it up. In short: https://en.wikipedia.org/wiki/Sequence_point Basically it has to do with the sequence in which multiple ++i must be done in the same expression is undefined. So, even though it will most probably compile (I haven't tried), different compilers can/will probably give different results.
16th Dec 2016, 10:48 AM
Ettienne Gilbert
Ettienne Gilbert - avatar
+ 1
compiler.... first step: calculation of operand values...++i =6...++i=7 Hence at the end of first step, value of variable i=7 second step: arithmatic operation i=7+7=14 will be answer
16th Dec 2016, 10:54 AM
Manikanta Nallamalli (Mittu)
Manikanta Nallamalli (Mittu) - avatar
0
@Tnx gilbert :) I agree to what he mentioned...it's a compiler,language based question
16th Dec 2016, 2:33 PM
Manikanta Nallamalli (Mittu)
Manikanta Nallamalli (Mittu) - avatar