I sometimes find that using bools in integer expressions make for shorter and simpler code. For example I prefer
int n_items = has_a + has_b + has_box * 5;
over
int n_items = (has_a ? 1 : 0) + (has_b ? 1 : 0) + (has_box ? 5 : 0);
This should be safe since false==0 and true==1. Are the any risks or gotchas one should know about?
With bools I mean either C99 bools or boolean expressions like a>b
. Of course I have to watch out for values that are not actually boolean, like the return value of isdigit()
.