Robust Booleans in C
Posted: Thu May 12, 2005 1:30 am
Hi. I am new to the Blender codebase, and I am impressed by the work you're all doing. That said, C lacks an explicit boolean type which traditionally causes some confusion and irregularities in coding style. Remember, in C, booleans are evil, and they'll seek to destroy your sanity.
Ton style
Ton made some excellent notes here which everyone should review. In addition to what he wrote, I occasionally see the likes of:
which will bite you. Even if x is zero, which is the only safe case to do this, the following is friendlier to read:
Bugs! (The really, really evil kind).
Here's a disaster waiting to happen:
Here's the reason:
Note that b could never be true in this example.
Worse yet, the most virulent complaint the compiler will give you is a weak type error warning. And to rub it in, it will probably claim to have fixed the error. This will provide many happy nights of bug-hunting.
Whoever gets to it first should modify BKE_utildefines.h with the following, right underneath the definitions of TRUE and FALSE:Every parenthesis is important. (I haven't commit priveledges yet.)
Now, our mysterious bug can be obviated thus:
No matter what happens, your function is now forevermore guaranteed to get a correct and proper boolean value.
Egads! More yapping!?
No, not really.

Ton style
Ton made some excellent notes here which everyone should review. In addition to what he wrote, I occasionally see the likes of:
Code: Select all
if (my_bool_var == x) ...
Code: Select all
if (my_bool_var) ...
if (!my_bool_var) ...
Here's a disaster waiting to happen:
Code: Select all
my_bool_arg_func( my_bit_flags & BF_FOO );
Code: Select all
void my_bool_arg_func( short b );
#define BF_FOO 0x10000

Whoever gets to it first should modify BKE_utildefines.h with the following, right underneath the definitions of TRUE and FALSE:
Code: Select all
#define BOOL( x ) ((x) ? (TRUE) : (FALSE))
Now, our mysterious bug can be obviated thus:
Code: Select all
my_bool_arg_func( BOOL( my_bit_flags & BF_FOO ) );
Egads! More yapping!?
No, not really.
