Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator precedence [duplicate]

Tags:

c++

operators

Possible Duplicate:
cout << order of call to functions 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;
}
like image 441
Fabio Dalla Libera Avatar asked Aug 23 '12 06:08

Fabio Dalla Libera


1 Answers

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

According to §6.2.2 of Stroustrup's The C++ Programming Language, Third Edition...

The order of evaluation of subexpressions within an expression is undefined. In particular, you cannot assume that the expression is evaluated left to right.

§5.4 of the C++03 standard specifies:

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. Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

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

like image 149
obataku Avatar answered Sep 28 '22 05:09

obataku