Reputation: 1874
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?
Upvotes: 39
Views: 34302
Reputation: 14530
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
.
Upvotes: 15
Reputation: 36649
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.
Upvotes: 2
Reputation: 755006
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.
Upvotes: 10
Reputation: 122493
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.
Upvotes: 46