Return value of "==" operator in C

Solution 1:

Can I assume that in C, the "==" operator will always evaluate to 1 if the two values are equal or it can evaluate to other "true" values?

Yes, and so does != > < >= <= all the relational operator.

C11(ISO/IEC 9899:201x) §6.5.8 Relational operators

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.107) The result has type int.

Solution 2:

From the standard :

6.5.8 Relational operators

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. The result has type int.

6.5.9 Equality operators

The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence. Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int. For any pair of operands, exactly one of the relations is true.

For logical operands (&&, || ) :

6.5.13 Logical AND operator ( or 6.5.14 Logical OR operator )

The && (or ||) operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

You can check the last draft here : http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

Conclusion :

  • All the equality and relational operator (==, !=, <, >, <=, >=) return 0 for false and 1 for true.

  • The logical operators (==, ||, !) treat 0 as false and other values as true for their operands. They also return 0 as false and 1 as true.

Solution 3:

The comparison (equality and relational) operators (==, !=, <, >, <=, >=) all return 0 for false and 1 for true — and no other values.

The logical operators &&, || and ! are less fussy about their operands; they treat 0 as false and any non-zero value as true. However, they also return only 0 for false and 1 for true.