+ 1
why the output of below code is different in c++ and java?
int a =10, b=10;for(int i=0;i<2;i++) {a = a+ a++; sout("The result of a+ a++ = " +a;)} for(int i=0;i<2;i++) {b=b+ ++b;sout("The result of b+ ++b="+b)} The output of above code in c++ is:- The result of a+ a++ = 21 The result of a+ a++ = 43 The result of b+ ++b = 22 The result of b+ ++b = 46 but the output of same code in java is:- The result of a+ a++ = 20 The result of a+ a++ = 40 The result of b+ ++b = 21 The result of b+ ++b = 43 why this strange is happening?
8 Answers
+ 4
++var increments the value of var before useage.
var++, after useage.
This means that a+ a++
a is initially 10
a is added to a.
a becomes 11.
The sum=20.
b is initially 10
b become 11
b is added to the first b.
The sum=21
+ 2
How is Java even here?
+ 2
I m agree with u @$Vengat
but in c++ it gives different output
+ 1
@Shawn Daley
if c++ evaluate from right to left then comment about this line
a=b-a+(b=a)
this swap a and b
+ 1
some expressions are well defined, some are not (like k = k++ + ++k). ambiguous expressions valuation depends on the compiler. just avoid them! see:
http://en.cppreference.com/w/cpp/language/eval_order