Why integer booleans?

Nov 20, 2009 at 6:21pm
closed account (S6k9GNh0)
I find that many people redefine integers to be booleans. As a boolean can easily be represented as a single bit with 0 or 1, I cannot help but not understand this. What advantages does defining and using an integer as a boolean give you?
Last edited on Nov 20, 2009 at 6:23pm
Nov 20, 2009 at 6:34pm
I don't think it is so much a advantage as a habit as boolean is a newer type and most programmers are used to using 0 and 1.
Nov 20, 2009 at 6:38pm
Agreed here. It wasn't even a type in C until C99 I believe. I started with C++ so I've always used bool/true/false, but if someone is used to ints it might be faster for them even at the memory cost.
Nov 20, 2009 at 7:01pm
It's a clarity thing.

If a varialbe is boolean you know it represents a true/false condition that can be toggled.

If a variable is an integer it could be anything. And while it's true you can treat integers as booleans, there's no way to immediately know that this is what the program is doing from an outside observer.


It's the same thing as using typedefs, enums, etc. Sure you don't have to, but it makes the code easier to maintain/follow/understand.

EDIT:

doh -- you were asking why integers were used as booleans! Not the other way around. I totally misunderstood. My mistake.

Oh well. ^^
Last edited on Nov 20, 2009 at 7:04pm
Nov 20, 2009 at 7:54pm
As a boolean can easily be represented as a single bit with 0 or 1,


While a bool can be represented as a single bit, it hardly ever is. Do a sizeof on a bool in most compilers in you'll be hard pressed to find any smaller than a byte.
Nov 23, 2009 at 1:42am
Booleans are 1 byte and Char's are 1 byte. The compiler doesn't allow use to work on the bit-level. However, we can use bitwise operators.
Nov 23, 2009 at 2:57am
I can't find it in the standard, but I don't think bools are guaranteed to be of any size, and chars are definitely not guaranteed to be 1 byte long (although all implementations I know of follow this convention).
Nov 23, 2009 at 4:10am
IIRC, chars actually are guaranteed to be 1 "byte" long... but 1 "byte" is not necessarily 8 bits.

sizeof(char) is always guaranteed to be 1, though.
Nov 23, 2009 at 9:17pm
char myChar = 'h';

myChar is 1 byte.

char myChar[] = "abcdefghijklmnopqrstuvwxyz";

Obviouslly more than 1 byte, but still 1 byte for each character nontheless.
Topic archived. No new replies allowed.