Char or Int for boolean value in C?

16.8k views Asked by At

I find that there is no native bool type. People either use int or char - though it seem that int might be more frequently used than char? Is this true?

My first impulse was to use char as it is a smaller data type, but there something I've missed? Is int better for boolean values, and if so - why?

5

There are 5 answers

5
cnicutar On BEST ANSWER

There is a _Bool in C99, and a bool if you include stdbool.h.

If you don't have it (a decently modern compiler), use int, it's usually the fastest type. The memory savings of using char are likely negligible.

0
Nicholas On

According to ISO-9899 the result of relation, logical and equality operators has type int. true and false from stdbool.h are also integers. If you want to spare memory - use bit-fields.

0
Paul R On

If you're using a reasonably modern C compiler then you just need:

#include <stdbool.h>

This typically has a macro such as:

#define bool _Bool

which lets you use C99's built-in _Bool type wherever you need a bool.

0
Jerry Coffin On

There is a native type named _Bool (starting with C99). In <stdbool.h>, there's also a #define to provide bool as an alias, if you want it (also has #defines for true and false).

2
BlackBear On

Actually there's no real difference since char gets always promoted to int when using it (check this). I have never seen a char used as a bool though, so I'd go for using an int.