Tor Klingberg
Tor Klingberg

Reputation: 5088

Are there any risks or gotchas when using C bools as integers

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().

Upvotes: 2

Views: 121

Answers (1)

ouah
ouah

Reputation: 145829

One of the risk with bool is it has a different semantic than int and a lot of programs already use bool as an alias to int and are not using C99 _Bool typedef from stdbool.h (e.g., programs developed for C89 or meant to be compatible with):

typedef int bool;

Then this expression for example may have different meanings:

int a = (bool) 0.5;  // if bool is _Bool, evaluates to 1
                     // if bool is int, evaluates to 0

This can create some really nasty bugs.

On other hand a shorter form than (has_a ? 1 : 0) is the idiomatic !!has_a.

Upvotes: 4

Related Questions