3 ms·
I disagree. I avoid implicit casting, including truthiness. "== true" is indeed suspicious because you aren't avoiding anything, but to me "!= 0" or "!= nullptr
by twiceaday 4y ago
I disagree. I avoid implicit casting, including truthiness. "== true" is indeed suspicious because you aren't avoiding anything, but to me "!= 0" or "!= nullptr" are crisper.
- userbinator 4y agoI don't know what you mean by "crisper", but in general I've noticed that extraneous code only increases the chance of bugs (and this is a good example of that.) if(foo) and if(!foo) are very common idioms and should be committed to the subconscious memory.
- WirelessGigabit 4y ago!= 0 should only be used for ints / floats / 'numbers'. Comparing it to false requires me to know that false is 0. Comparing it to a ptr requires me to know that 0 represents a pointer pointing to nothing.
- djur 4y ago0 is the false value in C, no implicit casting or "truthiness" involved. The C standard explicitly defines if statements in terms of zero: "the first substatement is executed if the expression compares unequal to 0... [else] is executed if the expression compares equal to 0". C does not have a boolean type. (The `true` and `false` defined in stdbool.h are macros expanding to the integer literals 1 and 0, respectively.)
- 3836293648 4y agoC has a boolean type, it just doesn't have true and false constants in that type.
- pjmlp 4y agoC23 replaces them with proper keywords.
- djur 4y agoYes, although they still evaluate to 0 and 1 and conditional logic is still defined in terms of 0 and 1. Maybe that will change at some point in the future as well!
- UncleEntity 4y agoThey aren’t testing for ‘false’ in this case but for success. Functions which return 0 on success I always compare with 0 as “if (foo()) error();” easily gets confusing. If I see “if (foo() != 0) error();” then I can easily tell what’s going on because C is funny like that. Conversely, if I’m testing for truthfulness or NULL I’ll use the boolean operators.