I'm curious about the best practice for representing boolean values in C. Specifically, is it better to use an int or an unsigned 1-byte type? I know that bool was introduced in C23, but what if I'm using an older standard? Are there any advantages or disadvantages to using one over the other?
3 Answers
I lean towards using an int because it's memory aligned and tends to offer better performance. Just check how your system handles it, especially on 64-bit systems - might still be aligned. But honestly, I think int is a safe bet for booleans.
Honestly, just go with int. All the comparison operators work fine with it, and if you use stdbool, you're already relying on int under the hood. I’d only consider packing booleans into 1-byte types if you're really scraping for memory, like in microcontroller projects or something.
Do you think packing booleans in a struct could cause alignment issues? Just clarifying.
I remember back when RAM was precious, I packed bits into bytes to get more booleans. It worked but was a pain with bit manipulations!
If you're using a C version before C23, both int and unsigned int work well for representing booleans. Actually, you can even use char, short, or long if you want! But don't forget about stdbool.h, which defines bool for you. So if you're on C99 or later, just stick with that for clarity.
That's a good point! The _Bool type existed before too, right? I think it's solid for older C.
Does that mean long would be necessary on 64-bit? Just trying to figure out memory alignment here.