3 ms·
// Of course this is only an example, but except in rare cases when the value of a boolean is significant (e.g., interfacing code in different languages), don't
by getpost 12y ago
// Of course this is only an example, but except in rare cases when the value of a boolean is significant (e.g., interfacing code in different languages), don't compare to booleans! Not only is it redundant, it's another potential source of error.
if (!c_assert(p >= 0) == true) {
return ERROR;
}
// vs
if (!c_assert(p >= 0)) {
return ERROR;
}
// The following makes the error condition clearer, but it goes against the convention of having a hopefully true condition as the argument to assert.
if (c_assert(p < 0)) {
return ERROR;
}
- asynchronous13 12y agoI agree with you in principal, but in practice I work on a lot of C code that does not have a built in bool type (C89). In your example using > or < there is not an issue because it's certain the return value is either 0 or 1. However, when checking a specific variable used as a boolean I prefer to see an explicit comparison. if(variable) versus if(variable==TRUE) I developed this preference after spending weeks on a particularly nasty bug. The bug was triggered by a corrupted int that was used as a boolean variable that passed a check because if(146134613) { kill_me_now(); } will run, even though the value had been corrupted. (of course, tracking down the source of the corruption was the real fix for that case, but there's no point in having safety checks that don't work)
- getpost 12y agoInteresting example, but then you're at risk of creating code paths that vary depending on whether boolean values are true, false, or other, which is contrary to the definition of a boolean value.
- asynchronous13 12y agoYou're right, but that is true because there is not a boolean type, not because of the form of the check. Either form has the same problem since an int is used in place of a true boolean (true | false | other), but I prefer the form that makes it more explicit and noticeable.