Reputation: 675
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
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
Reputation: 9861
You need to understand
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
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