Ansh David
Ansh David

Reputation: 672

Comparison of int values in an if statement

I had a question in my test paper in which we had to compare the values of int type variables. The first thought that came to my mind was that it was missing the && operator but i am not sure.

int a=2, b=2, c=2;
if(a==b==c)
{
    printf("hello");
}

I have a doubt, will the above statement will execute or not in c or c++? Can i have the reason as well. Thank You

Upvotes: 0

Views: 4475

Answers (4)

Polymorphism
Polymorphism

Reputation: 249

a == b == c is a comparison between c and result of a==b (1 or 0) operation.

Upvotes: 0

user2540082
user2540082

Reputation: 27

use a==b&&b==c. the condition a==b==c is equivalent to (a==b)==c which will provide the required result iff c==1, else the code will fail.

Upvotes: -1

ouah
ouah

Reputation: 145829

a==b==c

is equivalent to

(a == b) ==  c

The result of a == b is 1 (if true) or 0 (if false), so it will probably not achieve what you expect.

Use a == b && b == c to check if the value of the three objects are equal.

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258568

It will execute but with what I believe unexpected results to you.

One of the == will evaluate to a boolean value, which will then be converted to an int and then the second comparison will be performed, comparing an int to either 1 or 0.

The correct statement is a==b && b==c.

For example:

3 == 3 == 3

evaluates to

true == 3
1 == 3
false

Upvotes: 10

Related Questions