Trevor Hickey
Trevor Hickey

Reputation: 37894

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

I want to make sure that all 3 conditions result in the same answer before executing a 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 those 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 does my first example not work?

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 method of evaluating doesn't work.
It recently came to my attention while writing an if statement that determines if an nxn array is a magic square or not.

Upvotes: 3

Views: 2278

Answers (2)

sarnold
sarnold

Reputation: 104080

This portion results in a boolean or integer, 0 or 1:

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

So the rest of the expression looks like:

1 == (4 + 0)

or

0 == (4 + 0)

Neither of these are correct.

The only operator that takes three arguments is the foo ? bar : baz operator. Everything else takes one or two arguments.

Upvotes: 1

Imp
Imp

Reputation: 8609

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

First, (2 + 2) == (1 + 3) evaluates to true, because it really holds that 4 == 4.

Then, you're comparing true == (4 + 0). In this case, boolean values are casted to integers:

true -> 1
false -> 0

Therefore you're comparing 1 == 4, what results in false.

Upvotes: 12

Related Questions