条件表达式行为不正确

时间:2015-09-27 22:09:41

标签: c++ c++11

我希望这两个条件会产生相同的答案(nEntries = 0)。我不明白为什么没有。

# include <stdlib.h>
# include <iomanip>
# include <iostream>

using namespace std;

    int main() {
       int nEntries = 1;
       nEntries = (nEntries)? nEntries--: nEntries;
       cout << "nEntries = " << nEntries << endl;   // nEntries = 1
       nEntries = 1;
       if (nEntries) nEntries--;                    // nEntries = 0
       cout << "nEntries = " << nEntries << endl;
       return 0;
}

看起来条件表达式正在执行:

if (nEntries) tmp = nEntries--;

本领域

1 个答案:

答案 0 :(得分:3)

nEntries = (nEntries)? nEntries--: nEntries; // statement 1
// ...
if (nEntries) nEntries--;  // statement 2

1和2是 not 等效语句,因此没有理由期望它们的行为相同。

// statement 3, equivalent with statement 1
if (nEntries)
     nEntries = nEntries--; // Assignment and decrement are unsequenced modifications.
                            // The behaviour is undefined.
else
     nEntries = nEntries; // this is pointless...

如您所见,语句1及其等效3具有未定义的行为,因此您不能指望它以任何特定方式运行。

如果您不熟悉未定义的未定序修改,请参阅Undefined behavior and sequence points