+ 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?

11th Sep 2017, 7:00 AM
Danish
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
11th Sep 2017, 6:28 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
How is Java even here?
11th Sep 2017, 6:27 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
I m agree with u @$Vengat but in c++ it gives different output
11th Sep 2017, 7:26 AM
Danish
+ 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
11th Sep 2017, 9:35 AM
Danish
+ 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
11th Sep 2017, 10:02 AM
yuri