3

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

e2p
  • 137
  • 1
  • 8
  • I'm not sure how you get `b: 5` when you're using post-increment. Is this the exact code you're using? – David Brown Dec 09 '13 at 20:43
  • I'm sorry, I forgot. post-increment returns new value as integer. – e2p Dec 09 '13 at 20:45
  • @kolumb Then you've implemented prefix `++` and called it postfix. Your code's future maintainers will find this hard to grasp at the very least. – Mark B Dec 09 '13 at 20:47

3 Answers3

6

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.

David Brown
  • 13,336
  • 4
  • 38
  • 55
1

The order of the evaluation is unspecified.

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

Community
  • 1
  • 1
Marcassin
  • 1,386
  • 1
  • 11
  • 21
1

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.

Community
  • 1
  • 1
lwi
  • 1,682
  • 12
  • 21