|
|
|
|
|
by mbell
4674 days ago
|
|
Consider a simple bit mask operation, assume 8 bit ints for the sake of brevity: Prior to C99, assuming you use the mentioned typedef for bool: bool a = someInt & 0x02
'a' will be 0x02 if the bit is set.In C99, bool is aliased to _Bool and if the flag is set, the above code will result in 'a' being 0x01 because of C99's requirements for type conversion. To accurately get the same behavior prior to C99, you can add !!, e.g.: bool a = !!(someInt & 0x02) //'a' is now 0x01 when the bit is set.
|
|
If you had written
or something similarly clear and unambiguous, nothing odd would happen, even in C.(Edit: OK, that's not strictly true, because of the operator precedence order. It's never made sense to me that integer arithmetic operators have higher precedence than comparisons but bitwise logical operators have lower precedence, so if you remove the parentheses above then the resulting code doesn't do what you'd expect. I suppose this is because I'm looking at the problem as if comparison operators return a proper boolean value rather than an integer, and the ordering we've wound up with in C dates from a historical oddity about 40 years ago.)
The underlying problem with booleans in C99, as Linus and others have been saying, is that the language doesn't actually enforce basic type safety, so cases like your first example
that should result in a type error are allowed through, and with odd results: how does it make any sense for a boolean variable to have an integer value like 0x01 or 0x02?Then programmers who relied on such odd results wind up writing horrific code like your second example
where fudge factors build on top of distortions to make the old hacks work.And then we wonder why in 2013 we still have widely used, essential software that is riddled with security flaws and crash bugs. :-(