-5

i use vs2010 compiler and i face an ambiguity

what does the code below means? what is the output and why?

    int a;
    cout<<(a=2)+(a=3)+(a=5)

im so sorry if the question is asked before or if it is obvious! but i am confiused for the result

   output :15

I COULD NOT FIND MY ANSWER HERE:

Why are these constructs (using ++) undefined behavior?

be patient and look at the result again (please)

thanx in advance

Community
  • 1
  • 1
mefmef
  • 665
  • 2
  • 11
  • 23

2 Answers2

3

what does the code below mean?

Nothing sensible.

what is the output?

Unpredictable.

and why?

Because this code invokes undefined behavior.

1

That standard says the order of evaluation of parallel sub-expression within an expression is not defined. In your example, compilers have freedom to choose which one to evaluate first and the result is therefore not predicable

  • could u explain in what order the 15 result appears? – mefmef Feb 14 '13 at 20:35
  • @mefmef The code invokes *undefined behaviour.* This means *anything* can happen (it could open up your media player and play something if it really wanted). Probably the compiler issued instructions which don't translate to the code exactly. As the code is invalid, it's perfectly legal for it to do that. – Angew is no longer proud of SO Feb 14 '13 at 21:07
  • @mefmef - There is no order. You try to change the value of `a` several times in the same expression. That's not allowed, and results in undefined behavior. **Any** result is possible, including crashing the system (or outputting 15, or something else). – Bo Persson Feb 14 '13 at 21:08