I'm trying to decide whether it's better to use an int or an unsigned 1 byte type to represent a boolean in C. I've heard mixed opinions, especially since bool was introduced in C23, but I'm also curious about older standards. What are the pros and cons of each option?
3 Answers
If you're on the latest C standards like C23, you can use the built-in bool type, but if you're using something older, both int and unsigned int work fine for boolean representation. You can even get creative and use other types like char or short. Just keep in mind that using stdbool.h makes things easier!
Honestly, just use int. It works great with all comparison operators and conditionals, plus C looks for integers with bool from stdbool. If you're in a super tight memory spot, then maybe think about that 1 byte type, but it’s rarely worth it outside of extreme cases.
But why would you pack boolean flags in a struct? I feel like that could create all sorts of alignment issues, right?
Back in the day, when RAM was actually limited, I once packed 16 booleans into just 2 bytes to save space. It worked, but it did need a lot of bit manipulations to handle properly!
I'd lean towards using an int since it's memory-aligned and tends to perform better. Just be cautious on 64-bit systems where long may come into play for alignment.
Right, but do you always need to worry about alignment on 64-bit? Or are there cases where int still holds up?
Yeah, and don't forget that before C23, we had _Bool, which was available in earlier standards. So technically, bool has been around for a while once you include stdbool.h from C99.