Not that my opinion is more valid than anyone else posting, but i thought i'd add it on this one. The failure of C to include a boolean type, and force only that type to be used in a conditional is a serious flaw. It's not the end of the world, people obviously get by without it, but it can lead to some real sloppiness and some serious errors.
The BOOL typedef that's used in Objective-C is nice, TRUE and FALSE are #defined to 0 and 1 on a lot of systems as well. This sort of helps with readability, but doesn't address the real problem.
For example:
This will be true as long as y is non-zero. In general, the intent is to use == to evaluate equivalence, not = for assignment, but an assignment expression evaluates to its second operand so you can do things like:
It also leads to people using if statements to check for nullity since a null pointer is equal to 0, etc. This seems pretty sloppy to me, because in english you want to ask "Is this pointer (non-)null?" not "Is this pointer?". While computer science has strong ties to logic and philosophy, the latter doesn't really make sense in this context. For this reason i would prefer that a logical operator be used in cases like this, so you say:
Code:
if(myPtr != null) {
...
}
or
i
so what you're checking for is explicit.
In this magical world where C supports a real boolean that must be used in an if statement, if you had a function that returned a boolean type, it would be perfectly correct (and readable, in my opinion if the function was named nicely) to just check its return value. In this imperfect world of typedef'd BOOLs, usw. we're stuck with the debate at hand, and some very difficult to read code out there.
One workaround for the issue Steve mentioned (possibility of an external function that returns a BOOL not returning 1/YES for "truth") would be to only check against NO. This would either require you to always switch the if and else portion of your control structure, or check if things are != to NO instead of == to YES. It's ugly, but it would be "safer" than just using == YES for the reasons Steve mentioned.
This doesn't really lead anywhere, but I thought i'd chime in because of some of the horrors i've come across (and assuredly I've written) that depend on this strange behavior. I understand on a lot of microarchitectures there's a JNE or JEQ sort of instruction that only checks against 0, which makes mapping easy... but a little more work in this area originally would have gone a long way in my opinion.
-Lee