Search code examples
c++pre-incrementcoverity

Does the placement of a pre-increment operator make a difference here?


In the following C++ code is there a difference between the values of x and y at the end?

const int LoopLength = 100;
unsigned short x = 0;
for (int i = 0; i < LoopLength; i++)
{
    x = ++x % 2;
    cout << x;
}

cout << endl;

unsigned short y = 0;
for (int i = 0; i < LoopLength; i++)
{
    ++y = y % 2;
    cout << y;
}

cout << endl << (x == y) << endl;

Coverity (static-analysis tool) claims that the order in which the side-effects take place is undefined with a line like x = ++x % 2;. I'm unsure if I should worry about it.


Solution

  • Both forms are totally undefined prior to C++11 because they both write to the same memory location without an intervening sequence point.

    According to the linked question So why is i = ++i + 1 well-defined in C++11? the first form is legal in C++11, due to more restricted sequencing of writes.

    I believe that the second case is not well defined as the order of evaluation of the operands to = are not specified.

    Luckily all these questions can be avoided by never ever writing code that anywhere near resembles this. Your future code maintainers will thank you and send you gifts from the future.