1

I was asked in a job interview what would the following code in C++ would output to screen:

int i = 3;
cout << (++i + i++ - ++i + i++);
return 0;

In my computer it outputs 9, but why? Is this undefined?

Magnus
  • 514
  • 2
  • 7
  • 19
  • Pre increment increments variable value first and then process and post increment does first process then increment, here answer 9 is correct because 4 + 4 - 6 + 6 is evaluate to 8 but because of your last ++ operation which is still not evaluated is evaluated at last, hence it become 9. – Pramod Gaikwad Dec 15 '15 at 03:01
  • @PramodGaikwad no that is wrong – M.M Dec 15 '15 at 03:33

1 Answers1

1

yes this is system dependent. Behavior not defined because of that. Here which will be computed first ++i or i++ is different. This is unspecified.

user2736738
  • 30,591
  • 5
  • 42
  • 56