'Return value of "==" operator in C
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?
struct ss {
int id;
};
struct os {
int sid;
int state;
};
int count(struct ss *s, int state)
{
int num = 0;
// foreach o (of type os*) in a hash table
num += o->state == state && (s ? o->sid == s->id : 1);
return num;
}
So o->sid == s->id will return always 1 or 0, or it can return other values?
Solution 1:[1]
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 (
==,!=,<,>,<=,>=) return0forfalseand1fortrue.The logical operators (
==,||,!) treat0asfalseand other values astruefor their operands. They also return0asfalseand1astrue.
Solution 2:[2]
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.
Solution 3:[3]
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, for a standard compliant compiler, this assumption is correct:
Programming languages — C, §6.5.9 Equality operators (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf):
Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
