Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to neatly avoid C casts losing truth

Tags:

c

coding-style

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?

like image 701
me_and Avatar asked Jan 21 '10 16:01

me_and


3 Answers

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.

like image 158
jarnbjo Avatar answered Nov 16 '22 11:11

jarnbjo


I'd prefer (flags & CONST_FLAG) != 0. Better still, use the _Bool type if you have it (though it's often disguised as bool).

like image 5
Jerry Coffin Avatar answered Nov 16 '22 10:11

Jerry Coffin


Set your compiler flags as anally as possible, to warn you of any cast that loses bits, and treat warnings as errors.

like image 4
Thomas Avatar answered Nov 16 '22 12:11

Thomas