Is !!x equivalent to x here?
Is !!x equivalent to x here?
It fits semantically with "I'm using x as a boolean, but it may not be 1".
I use !=0 in only one context, if(strcmp(a,b) != 0) to check if two strings differ. Normally if an if() expression I don't check explicitly for 0 or not 0, except for strcmp class of functions, because of the ordered comparison of it (<0, 0, >0) , its "boolean" value is inverted, so somewhat counter intuitive if used with implicit boolean values.
Cast to bool has me extremely nervous because ... It works in C99's _Bool type, but I have lots of bad memories of security bugs when using this approach with pre-standard custom bool types, which are still in common use including but not limited to Win32 and COM, or Objective-C.
The bug I am thinking of looks like this:
long long ll = 1LL << 32;
bool b = ll;
puts(b ? "yes" : "no");
I just tested to confirm. This prints "yes" when using C99 stdbool, presumably because they standardized it to work. If you change bool to a common choice for pre-standard bool typedefs (int or char, say), it prints "no" because the large nonzero value doesn't fit in that type. "Just use the standard type" you might say. But if we were working somewhere that required legacy nonstandard bools that is not our choice, and further, a later refactor on may start using those other types some day even if we make the correct choice today. So there is an argument to be consistent about avoiding this type of bug.Any nonzero expression is true, and 0 is false. But the result of !, or ==, ||, or any of those other boolean operators is 1 for true.
Recall relatedly that C didn't have a bool type until the 1999 standard, which introduced <stdbool.h>. C++ had it earlier, but for a long time the C way to store a boolean expression into a variable might have been int, or some nonstandard typedef. This is why so many libraries and frameworks in the C world define their own boolean type.