Reputation: 31617
Does the C standard ensure that the boolean operations (==
, !=
, >
, &&
, ||
, etc) always have the same value to represent truthfulness? In other words, do they always return some positive constant if true, or is the only guarantee that it will be a positive number?
The reason I'm asking this is to know if statements such as the one below are valid. That expression should be true if both pointers are NULL or both pointers point somewhere (not necessarily the same place).
if ((ptr1 == NULL) == (ptr2 == NULL))
Upvotes: 3
Views: 154
Reputation: 882806
Yes, although the rule for interpretation of integral values as boolean values by C states that 0
is false and any other value is true (a), the results of comparison operators is always 1
or 0
.
So the expression (a == b)
will never give you 42
, for example.
The relevant bits of the standard (C11) are all under 6.5 Expressions
:
6.5.8/6: 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.
6.5.9/3: 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.
6.5.13/3: The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0.
6.5.14/3: The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0.
That covers all the ones you explicitly mentioned in your question. The only other boolean operation I can think of (off the top of my head) is the logical NOT operator !
which is also covered:
6.5.3.3/5: The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0.
(a): See C11 sections dealing with if
, while
, do
and for
, which all contain language along the lines of something happen if/while "the expression compares unequal to zero"
. Specifically:
6.8.4.1/2: In both forms [of the if statement, one with and one without an else clause], the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0.
6.8.5/4: An iteration statement [while, do and for] causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0.
Upvotes: 7
Reputation: 145919
The results of
negation operator (!
)
relational operators (<
, >
, <=
, >=
)
equality operators (==
, !=
)
logical operators (&&
, ||
)
is an int
value of either 0
(false) or 1
(true).
Upvotes: 0
Reputation: 400159
Yes.
Values generated by operators will always be 1 for true and 0 for false.
Upvotes: 1