一个条件(C/C++)中的多个表达式

multiple expressions in a condition (C/C++)

本文关键字:表达式 C++ 一个 条件      更新时间:2023-10-16

在执行控制块之前,我想确保所有3个条件都得到相同的答案:

#include <iostream>
#include <cstdlib>
int main(){
    ///BUT THIS DOES NOT WORK!
    if ( (2 + 2) == (1 + 3) == (4 + 0) ){
        std::cout << "not executed" << std::endl;
    }
    return EXIT_SUCCESS;
}

假设这些数字实际上是变量。这就是我要做的:

#include <iostream>
#include <cstdlib>
int main(){
    int n1 = 2;
    int n2 = 2;
    int n3 = 1;
    int n4 = 3;
    int n5 = 4;
    int n6 = 0;
    int a = n1 + n2;
    ///this works
    if ( (n3 + n4) == a && (n5 + n6) == a){
        std::cout << "executed!" << std::endl;
    }
    return EXIT_SUCCESS;
}

问题:为什么我的第一个例子不起作用

我可以为多个变量分配相同的值,如下所示:

#include <iostream>
#include <cstdlib>
int main(){
    int a,b,c,d;
    a=b=c=d=9;
    ///prints: 9999
    std::cout <<a<<b<<c<<d<<'n';
    return EXIT_SUCCESS;
}

希望有人能解释为什么这种评估方法不起作用
最近,我在写一个if语句时注意到了这一点,该语句确定nxn数组是否为幻方。

(2 + 2) == (1 + 3) == (4 + 0)

首先,(2 + 2) == (1 + 3)计算为true,因为它确实包含4 == 4

然后,您正在比较true == (4 + 0)。在这种情况下,布尔值被强制转换为整数:

true -> 1
false -> 0

因此,您正在比较1 == 4,结果为false。

此部分产生布尔值或整数01:

(2 + 2) == (1 + 3)

因此,表达式的其余部分看起来像:

1 == (4 + 0)

0 == (4 + 0)

这两者都不正确。

唯一接受三个参数的运算符是foo ? bar : baz运算符。其他一切都需要一两个论点。