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

I want to make sure that all three conditions result in the same answer before executing the control block:

#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;
}

      

Let's say these numbers are actually variables. This is what I have to do:

#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;
}

      

question: why is my first example not working?

I can assign multiple variables the same value like this:

#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;
}

      

hoping someone can explain why this estimation method is not working.
This recently caught my attention when writing an if statement that determines if an nxn array is a magic square or not.

+3


source to share


2 answers


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

First, it (2 + 2) == (1 + 3)

is evaluated as true

, because it really matters 4 == 4

.

Then you compare true == (4 + 0)

. In this case, boolean values ​​are passed to integers:



true -> 1
false -> 0

      

So you are comparing 1 == 4

which results in an error.

+12


source


This part results in boolean or integer, 0

or 1

:

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

      

So the rest of the expression looks like this:

1 == (4 + 0)

      



or

0 == (4 + 0)

      

None of them are correct.

The only operator that takes three arguments is the operator foo ? bar : baz

. Everything else takes one or two arguments.

+1


source







All Articles