【问题标题】:Assignment in if clause has no effectif 子句中的赋值无效
【发布时间】:2019-03-25 22:54:20
【问题描述】:

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

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

【问题讨论】:

  • 查找您正在使用的运算符的优先级。
  • 你在做if (show = (output || show))
  • 这就是为什么我假设任何if 语句包含一个没有正确括号赋值的赋值是错误

标签: c++ if-statement variable-assignment


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    if (show = output || show)
    

    一样
    if (show = (output || show))
    

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

    if ((show = output) || show)
    

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

    3
    show: 1
    show: 0
    

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 2011-10-30
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2011-10-31
      • 2021-08-13
      • 2015-07-15
      • 2020-08-07
      相关资源
      最近更新 更多