简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM