I'm quite happy that, in C, things like this are bad code:
(var_a == var_b) ? TRUE : FALSE
However, what's the best way of dealing with this:
/* Header stuff */
#define INTERESTING_FLAG 0x80000000
typedef short int BOOL;
void func(BOOL);
/* Code */
int main(int argc, char *argv[])
{
unsigned long int flags = 0x00000000;
... /* Various bits of flag processing */
func(flags & INTERESTING_FLAG); /* func never receives a non-zero value
* as the top bits are cut off when the
* argument is cast down to a short
* int
*/
}
Is it acceptable (for whatever value of acceptable you're using) to have (flags & FLAG_CONST) ? TRUE : FALSE
?
I would in either case called func with (flags & INTERESTING_FLAG) != 0
as an argument to indicate that a boolean parameter is required and not the arithmetic result of flags & INTERESTING_FLAG
.
I'd prefer (flags & CONST_FLAG) != 0
. Better still, use the _Bool type if you have it (though it's often disguised as bool
).
Set your compiler flags as anally as possible, to warn you of any cast that loses bits, and treat warnings as errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With