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))
Yes, although the rule for interpretation of integral values as boolean values by C states that
0is false and any other value is true (a), the results of comparison operators is always1or0.So the expression
(a == b)will never give you42, for example.The relevant bits of the standard (C11) are all under
6.5 Expressions: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:(a): See C11 sections dealing with
if,while,doandfor, which all contain language along the lines of something happen if/while"the expression compares unequal to zero". Specifically: