I'm wondering whether it's better to use an 'int' or an unsigned 1 byte type while working with boolean values in C. If you've got experience with different C standards, particularly older ones versus C23, I'd love to hear your thoughts! Are there specific situations where one is better than the other?
3 Answers
Honestly, just use 'int'. All the comparison operators work perfectly with it, and conditional statements expect it too. The only time I'd think about a 1 byte type is if you're dealing with extreme memory limits or packing boolean flags into structures.
Just a heads up, 'bool' isn't always the same size as 'int'. In some cases, like with certain ABIs, it might just be one byte.
Why would packing booleans in a struct change anything? Could there be alignment issues?
If you're using C23, you can work with 'bool' directly, but for older standards, both 'unsigned int' and 'int' work fine to represent a boolean. Even 'char' or 'short' could be used if you're adventurous! Just keep in mind that there's always 'stdbool.h' from C99 that helps with this too.
Right! Let's not forget that bool has been around since before C23, thanks to '_Bool' from earlier standards.
My inclination is to go with 'int' since it’s memory-aligned, making it faster to access. However, on a 64-bit system, you'll need to check if it's still aligned, or if you should use 'long'.
Good point! I'm curious if using a long is better for keeping things aligned.
Totally! Back in the day, I had to use unsigned integers to pack multiple booleans into a couple of bytes for performance. It did cost me some hassle with bit manipulations, though.