C++:三元运算符的歧义行为

C++ : Ambiguous Behavior of Ternary Operator

我尝试并测试了以下代码以了解三元运算符的行为。但这只会让我的事情变得复杂。 代码:

#include<iostream>
using namespace std;

void print(bool a, bool b, bool c) {
    int x, y, z, w;
    cout << (a ? (b ? x = 5 + b : y = 10 + b) : (c ? z = 15 + c : w = 20 + c)) << endl;
    cout << x << " " << y << " " << z << " " << w << endl;
}

int main() {
    cout << "Hello world!\n";
    print(false, false, false);
    print(false, false, true);
    print(false, true, false);
    print(false, true, true);
    print(true, false, false);
    print(true, false, true);
    print(true, true, false);
    print(true, true, true);
    return 0;
}

输出结果如下:

Hello world!
20
0 0 0 20
16
0 0 16 20
20
0 0 16 20
16
0 0 16 20
10
0 10 16 20
10
0 10 16 20
6
6 10 16 20
6
6 10 16 20

这看起来不像是遵循类似于标准 if-else 过程的过程。有什么猜测吗?

编辑:将变量初始化为一些随机整数(比如 -1)解决了这个问题。此外,它以某种方式在后续调用中重用了变量值。

您得到了奇怪的结果,因为您没有初始化 x、y 和 z 变量。 旧值正在重新使用。 用 0 初始化它们,你会得到不同的结果