Why integer booleans?

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
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.
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.
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
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.
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.
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).
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.
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.