0

I am trying to run this simple code

int a=0;
cout<<a<<a++;

but the output is not what I expected

10

I would expect "00" and a=1, why is the answer different?

Slazer
  • 4,750
  • 7
  • 33
  • 60
  • I've answered, but I'm willing to bet that this is a duplicate. – James Kanze Jul 21 '13 at 16:40
  • [Asked just few hours ago](http://stackoverflow.com/questions/17772464/c-code-displays-different-which-is-unexpected-output-in-different-compilers/17772778#17772778), same thing basically. Follow the links posted there, too. – jrok Jul 21 '13 at 17:00

3 Answers3

3

And what do you expect? Or more correctly, you're wrong to expect anything: you're modifying a variable, and accessing it for reasons other than determining the value to write, with no intervening sequence point, so the code has undefined behavior. It might output "10", it might output "01", or it might output "42", or even crash.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • 1
    You're saying cout << a << a++; is the answer to the universe ? – Floris Velleman Jul 21 '13 at 16:40
  • 2
    @FlorisVelleman Could be. Undefined behavior might actually be a very good answer to the universe. (Of course, undefined behavior might also send an email to all of your colleagues, inviting them to drinks down at the pub, on you. Or send an insulting email to your boss, telling him what you really think of him. Or generate a bank transfer from your account to that of the compiler writer.) – James Kanze Jul 21 '13 at 17:10
2

The C++ standard does not specify an order of execution for subexpressions

Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified...

DuncanACoulter
  • 2,095
  • 2
  • 25
  • 38
0

It is simple... As per my knowledge in C++ order of execution of any statement starts from right... in cout<

Siddhesh
  • 21
  • 2