6 ms·
IMO the intuition is to not use any intuition at all: there aren't built-in booleans in C, true is a #define for 1 and false is a #define for 0. For C condition
by nicklecompte 3y ago
IMO the intuition is to not use any intuition at all: there aren't built-in booleans in C, true is a #define for 1 and false is a #define for 0. For C conditionals, 0 = false, nonzero = true. So
a+b != 0 <=> a!=0 or b!=0
a*b != 0 <=> a!=0 and b!=0
Of course this intuition also reveals the pitfall behind this correspondence! You'd better make sure those are unsigned ints or #defined booleans, so you're not using general C expressions. 1 || -1 is true but 1 + (-1) is false.
Edit: forgot to mention: INT_MAX || 1 is true, but what about INT_MAX + 1 :)
- vzaliva 3y ago"true is a #define for 1" is bad idea. Because when `x` is, say, `2` then `if x` is not the same as `if x==true`.
- BenjiWiebe 3y agoThat's just the way C is. If you want to check "truthiness" (as much as you can in C), just do 'if x'.
- trealira 3y agoSomething nice in C is that "if (x)" is always equivalent to "if (x != 0)". NULL is a macro for 0, and so is false. Boolean expressions evaluate to 0 if they don't hold. This isn't true in C++, though.
- ahoka 3y agoThen what is _Bool, if not a built in boolean type?
- nicklecompte 3y agoI genuinely forgot stdbool.h existed, I don't actually write that much C myself. My point was more around the conditionals being weakly typed around unsigned ints rather than a specific lack of built-ins. A lot of commenters were going into arithmetic mod 2 or philosophical issues, neither of which actually apply here.
- kevin_thibedeau 3y ago_Bool isn't part of stdbool. It's a language keyword. C23 introduces full support for bool with true and false as keywords.