Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is (4 > y > 1) a valid statement in C++? How do you evaluate it if so?

Is that a valid expression? If so, can you rewrite it so that it makes more sense? For example, is it the same as (4 > y && y > 1)? How do you evaluate chained logical operators?

like image 612
trusktr Avatar asked Jan 17 '12 04:01

trusktr


People also ask

WHAT IS &N in C?

&n writes the address of n . The address of a variable points to the value of that variable.

What is the operation of in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.


1 Answers

The statement (4 > y > 1) is parsed as this:

((4 > y) > 1)

The comparison operators < and > evaluate left-to-right.

The 4 > y returns either 0 or 1 depending on if it's true or not.

Then the result is compared to 1.

In this case, since 0 or 1 is never more than 1, the whole statement will always return false.


There is one exception though:

If y is a class and the > operator has been overloaded to do something unusual. Then anything goes.

For example, this will fail to compile:

class mytype{
};

mytype operator>(int x,const mytype &y){
    return mytype();
}

int main(){

    mytype y;

    cout << (4 > y > 1) << endl;

    return 0;
}
like image 69
Mysticial Avatar answered Sep 20 '22 05:09

Mysticial