3 ms·
This is of course quite old, although C is older so it's not too bad. I really like the ones in the "Purity" section, and also appreciate the name, I sometimes
by unwind 1y ago
This is of course quite old, although C is older so it's not too bad.
I really like the ones in the "Purity" section, and also appreciate the name, I sometimes struggle to express those ideas. To me it's a lot about using the language as if you knew it, not from some strange position of fear that you sometimes see.
My pet peeve in the context is comparing boolean values with boolean literals, i.e.
const bool success = do_something();
if (success == true)
{
}
which is just horrible in my opinion since the result of an expression like `a == b` is in itself a boolean[*], so it just goes around and around, then! But nobody pretends that is true, since that would lead to
if ((success == true) == true)
which never happens, so for some reason in people's heads there is some significant difference between that and the first case ... which I find offensive. Always just write
if (success)
for the win.
Also, since nobody actually uses `const` as much as possible, using the explicit comparison also opens your code to the fantastic typo of:
bool success = do_something();
if (success = true) // Oops!
{
}
[*] In C it's more like "an int-type value equal to 0 or 1", I know, but logically that is a boolean in quite many ways.
Edit: markup asterisk failure.
- tialaramex 1y agoOne reason people think success == true is a good idea is they are (as in C) working with truthiness. In C "false" is truthy, and so is "" but 0 is falsy In a language where types aren't a gentle suggestion "false" is a string, so it can't be true or false, which are booleans. In such a language if (success) implies that success is a boolean, so the comparison is redundant. But C is not that language.
- kmoser 1y ago> if (success = true) // Oops! Hence the better way of comparing literals or consts to vars: if ( true = success ) // Compile-time error will enlighten you
- brontitall 1y agohttps://en.wikipedia.org/wiki/Yoda_conditions https://en.wikipedia.org/wiki/Yoda_conditions