As anything non-zero means true, but the >, <, == etc. operators returning 1 for true, I’m curious if there are any notable C compilers where these operators can result in a value greater than 1.
In other words, is there any compiler where int i = (a==b); would result in undefined behavior if I intended to use i not as a boolean value, but as an integer, and was assuming it would be either 0 or 1 ?
No, if there are, they’re not C compilers 🙂 The standard mandates that relational and equality operators return 1 for true and 0 for false.
The rule for interpretation of integral values as boolean values by C states that
0is false and any other value is true. See C11 sections dealing withif/while/do/for, which all contain language like"while the expression compares unequal to zero". Specifically:However, it’s quite explicit what result you will get for the comparison-type expressions, you either get
0or1. The relevant bits of the C11 standard for these are all under6.5 Expressions:And this behaviour goes way back to C99 and C89 (ANSI days). The C99 sections dealing with relational and equality operators also states that the return values is either 0 or 1.
And, while the C89 draft doesn’t explicitly dictate the return values for equality operators, it does say:
And the relational operators section does state:
Reference: http://flash-gordon.me.uk/ansi.c.txt since I don’t have any copies of the C89 standards floating around. I do have the second edition of K&R (the ANSI one from 1988) which basically says the same thing, in sections A7.9 and A7.10 of Appendix A, the Reference Manual. If you want a definitive answer from the first edition, that’ll have to come from someone with a wife less prone to throwing out old junk.
Addendum:
According to Michael Burr, who is either not married or has a more accommodating wife than I in terms of keeping old books 🙂