if 子句中的赋值无效

Assignment in if clause has no effect

考虑以下代码(我意识到这是不好的做法,只是想知道为什么会这样):

#include <iostream>

int main() {
    bool show = false;
    int output = 3;

    if (show = output || show)
        std::cout << output << std::endl;
    std::cout << "show: " << show << std::endl;

    output = 0;
    if (show = output || show)
        std::cout << output << std::endl;
    std::cout << "show: " << show << std::endl;

    return 0;
}

这会打印

3
show: 1
0
show: 1

所以,显然在第二个 if 子句中,output 的赋值,即 0,实际上并没有发生。如果我像这样重写代码:

#include <iostream>

int main() {
    bool show = false;
    int output = 3;

    if (show = output || show)
        std::cout << output << std::endl;
    std::cout << "show: " << show << std::endl;

    output = 0;
    if (show = output)  // no more || show
        std::cout << output << std::endl;
    std::cout << "show: " << show << std::endl;

    return 0;
}

如我所料,它输出:

3
show: 1
show: 0

谁能解释一下这里到底发生了什么?为什么 output 没有分配给第一个例子的第二个 if 子句中的 show?我在 Windows 10.

上使用 Visual Studio 2017 工具链

赋值没有发生,因为 || 的运算符优先级运算符高于赋值运算符。您分配输出 ||显示哪个是 0 || true 在第二个 if.

中的计算结果为 true

这与运算符优先级有关。您的代码:

if (show = output || show)

相同
if (show = (output || show))

如果你改变顺序,结果会改变:

if ((show = output) || show)

使用上面的 if 语句,它会打印:

3
show: 1
show: 0