post  Why integer booleans?

computerquip (876)   Link to this post
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
kenshee (19)   Link to this post
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.
Zhuge (633)   Link to this post
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.
Disch (2140)   Link to this post
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
jRaskell (291)   Link to this post
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.
Kangaroux (11)   Link to this post
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.
helios (6063)   Link to this post
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).
Disch (2140)   Link to this post
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.
Kangaroux (11)   Link to this post
char myChar = 'h';

myChar is 1 byte.

char myChar[] = "abcdefghijklmnopqrstuvwxyz";

Obviouslly more than 1 byte, but still 1 byte for each character nontheless.

This topic is archived - New replies not allowed.