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

时间:2012-04-02 01:21:08

标签: c++ c expression conditional-statements boolean-logic

我想确保所有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 个答案:

答案 0 :(得分:12)

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

首先,(2 + 2) == (1 + 3)评估为true,因为它确实支持4 == 4

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

true -> 1
false -> 0

因此,您要比较1 == 4,结果为假。

答案 1 :(得分:1)

此部分产生布尔或整数01

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

所以表达式的其余部分如下:

1 == (4 + 0)

0 == (4 + 0)

这些都不正确。

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