Operator Priority

Possible duplicate:
cout <order of calling functions that it prints?
Undefined Behavior and Sequence Points

Why does this code print 2 1 0?

#include <iostream> struct A{ int p; A():p(0){} int get(){ return p++; } }; int main(){ A a; std::cout<<a.get()<<" "<<a.get()<<" "<<a.get()<<std::endl; } 
+7
source share
1 answer

As I stated in my comment , there is no sequence point ...

According to ยง6.2.2 Stroustrup C ++ programming language, third edition ...

The procedure for evaluating subexpressions in an undefined expression. In particular, you cannot assume that an expression evaluates from left to right.

& sect; 5.4 of the C ++ 03 standard indicates:

Except where noted, the procedure for evaluating the operands of individual operators and the subexpressions of individual expressions and the order in which side effects occur are not defined. Between the previous and the next point in the sequence, the scalar object must have a value that its value is stored no more than once by calculating the expression.

You can learn more about sequence points and undefined behavior here .

+4
source

All Articles