-5
int main()
{
   int var = 1;
   var += ++var;
   cout<<var;
   return 0;
}

In Java this will output 3, as expected, but in C++ (above) it outputs 4. Why?

Danix
  • 1,947
  • 1
  • 13
  • 18
user1472747
  • 529
  • 3
  • 10
  • 25
  • @SeanBright lot of puppies would suffer for our learning purpose then =\ – Luiggi Mendoza May 21 '14 at 16:07
  • 1
    i dont think i have EVER seen `var += ++var;` in any context.. – celeriko May 21 '14 at 16:08
  • Java has well-defined semantics for the evaluation of such expressions, so the result you get is predictable there, as you note. It's simply not the case for C++ (or C). – Mat May 21 '14 at 16:10

1 Answers1

6

Because this is undefined behaviour. You're modifying and accessing the same variable without an intervening sequence point, so the outcome is really up to the compiler. If you compile this with clang, you'll see:

unsequenced modification and access to 'var'

I actually get 4 as the answer, but it could equally be 3, 7, 123125123 or "Lobster".

Adam Wright
  • 48,938
  • 12
  • 131
  • 152
  • 2
    I wouldn't consider "Lobster" to be equally likely... but point taken :-) – Sean Bright May 21 '14 at 16:08
  • 1
    Just to explain further: `var += ++var` is specified to be the same as `var = var + ++var`, and so the question of sequence would be "In `var + ++var`, which side is evaluated first?" If the left side is evaluated first then var won't have been incremented when we evaluate the left side. If the right side is evaluated first then the left side will have been incremented by the time we evaluate it. Java says that expressions are evaluated left to right. C++ doesn't specify an order and instead says that code that has this ambiguity does not have any defined behavior. – bames53 May 21 '14 at 16:22