首页 > 解决方案 > if 子句中的赋值无效

问题描述

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

#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

谁能解释这里实际发生的事情?为什么在第一个例子的第二个 if 子句中output没有赋值?show我在 Windows 10 上使用 Visual Studio 2017 工具链。

标签: c++if-statementvariable-assignment

解决方案


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

if (show = output || show)

是相同的

if (show = (output || show))

如果更改顺序,结果会更改:

if ((show = output) || show)

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

3
show: 1
show: 0

推荐阅读