Domanda

I have code like this:

std::cout << " a: " << classDate.getDays() << " b: " << classDate++ << " c: " << classDate.getDays();

I overloaded post-increment operator.

in class m_days variable has value:

  • before ++ operator - 4
  • after ++ oprator -5

My question is, why the results from cout are in wrong order:

a: 5 b: 5 c: 4

I checked it in debuger, values in class are correct. When I wrote the code like this :

std::cout << " a: " << classDate.getDays();
std::cout << " b: " << classDate++;
std::cout << " c: " << classDate.getDays();

everything is correct (a: 4 b: 5 c: 5).

Is that operator priority issue ?

Kamil

È stato utile?

Soluzione 2

The order of the evaluation is unspecified.

Take a look to this answer, a great explanation on this type of result

Altri suggerimenti

In C++ the order of evaluation of function arguments (and the overloaded operator<< used here is just a function) is undefined so the compiler is free to evaluate classDate++ as well as each classDate.getDays() in any order it chooses. So with different compilers or different compilation options you could get any of

a: 4 b: 5 c: 4
a: 4 b: 5 c: 5
a: 5 b: 5 c: 4
a: 5 b: 5 c: 5

If you want them to be evaluated in a specific order you should put the outputs in septate statements as in your second example.

My guess, the ++ operator is actually causing a side effect that is guaranteed to have taken place after a sequence point (see http://en.wikipedia.org/wiki/Sequence_point and Undefined behavior and sequence points).

Till reaching the seuqence point it is compiler dependent when the expression gets evaluated. So you cant rely on the evaluation order of your the expression.

In your second example there are sequence points after the semicolons, therefore it works as expected.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top