C++ evaluation order and possible outcome

72 views Asked by At

Consider following code:

#include <iostream>

int main()
{
    int i = 0;
    std::cout << ++i << ' ' << --i << std::endl;
}

In his "C++17 The Complete Guide" book Nicolai Josuttis writes that before C++17 this particular example might produce unpredictable results. Both 1 0 and 0 1 might be produced but what's more 0 0 is also a possible output. I don't get why the third sequence should be considered as possible. Either ++i or --i should be evaluated before the second value is evaluated which by definition cannot produce two zeros, shouldn't it?

1

There are 1 answers

0
yuri kilochek On BEST ANSWER

Before C++17, the 0 0 outcome was possible roughly like this.

  1. ++i is evaluated. i now stores 1. The result of this expression (which, importantly, is an l-value reference to i, not the r-value 1) is set aside as an argument to the << operator.
  2. --i is evaluated. i now stores 0. The result of this expression (which, importantly, is an l-value reference to i, not the r-value 0) is set aside as an argument to the << operator.
  3. << operators are evaluated, where both arguments are references to i which has value 0.