代码之家  ›  专栏  ›  技术社区  ›  kafman

if子句中的赋值无效

  •  1
  • kafman  · 技术社区  · 6 年前

    考虑下面的代码(我意识到这是一个糟糕的实践,只是好奇为什么会发生这种情况):

    #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
    

    有人能解释一下这里到底发生了什么吗?为什么是 输出 未分配给 show 在第一个例子的第二个if子句中?我在Windows 10上使用Visual Studio 2017工具链。

    2 回复  |  直到 6 年前
        1
  •  6
  •   HugoTeixeira    6 年前

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

    if (show = output || show)
    

    是一样的

    if (show = (output || show))
    

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

    if ((show = output) || show)
    

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

    3
    show: 1
    show: 0
    
        2
  •  2
  •   tsp    6 年前

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