marcinpz
marcinpz

Reputation: 675

Strange integer comparison in C

I am writing simple program in C and I can't see why:

printf("%d\n", 1 == 1 == 1);
printf("%d\n", 1 == 1);
printf("%d\n", 0 == 0 == 0);
printf("%d\n", 0 == 0);

Gives:

1
1
0
1

I'm used to Python so all this is new and strange to me.

(As an aside who was the inventor?)

Upvotes: 0

Views: 278

Answers (3)

ouah
ouah

Reputation: 145829

The result of the == operator is 1 if the two operands have the same value and 0 if the two values are different.

Upvotes: 2

satnhak
satnhak

Reputation: 9861

You need to understand

  1. Operator precedence (http://www.swansontec.com/sopc.html).
  2. That in C / C++ 0 is equivalent to false and any non zero integer is equivalent to true.
  3. The bool type is implicitly castable as an integer with 0 casting to false and 1 casting to true.

Thus 1 == 1 == 1 is evaluated as (1 == 1) == 1 --> true == 1 --> true. Whence printf("%d\n", 1 == 1 == 1) --> printf("%d\n", true) --> printf("%d\n", (int)true) --> printf("%d\n", 1) --> 1

Upvotes: 3

jpalecek
jpalecek

Reputation: 47762

I think C is for aliens, not humans.

Maybe. No human would write code as 1 == 1 == 1.

Anyway, what's going on here. The expression gets parsed AFAIK as (1 == 1) == 1, so it's a comparison of a result of another comparison with 1. Truth values are represented as integers in C; true is 1, false is 0. So 1 == 1 is 1 (true) and that is equal to 1.

With 0 == 0 == 0, it's similar:

(0 == 0) == 0
1 == 0 // 0 == 0 is true (1)
0 // 1 == 0 is false (0)

Upvotes: 12

Related Questions