c++ - if 子句中的赋值无效

标签 c++ if-statement variable-assignment

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

#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 工具链。

最佳答案

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

if (show = output || show)

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

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

if ((show = output) || show)

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

3
show: 1
show: 0

关于c++ - if 子句中的赋值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52919618/

相关文章:

c++ - BOOST-ASIO 阻塞服务器不响应阻塞客户端?

c++ - Lua项目编译出错(luabind)

matlab - 如何将 && 操作数求解为逻辑标量

javascript - 变量不会设置

c++ - 使用Excel模板内的OleFunction“查找”查找 header 变量,然后从C++替换它们

c++ - 我可以读取位于资源文件中的 .ini 文件吗?

r - "binning"行进入范围 (dplyr/R)

javascript - 我如何在 mustache.js 中做一个 if with value?

Google Go Lang 赋值顺序

postgresql - 数字类型 : "(0.0000000000000000,8)" 的输入语法无效