There's no boolean
in C Language, besides we can use non-zero int as true, otherwise false.
But if int size is 4 bytes, can we use char instead to have 1 byte of boolean?
There's no boolean
in C Language, besides we can use non-zero int as true, otherwise false.
But if int size is 4 bytes, can we use char instead to have 1 byte of boolean?
For further actions, you may consider blocking this person and/or reporting abuse
Saddam Hossain -
zarr -
Jacopo Marrone @tresorama -
Daniel Pepuho -
Top comments (8)
Oh come on... C has a (very basic)
bool
type since C99:; )
No, the actual Boolean type in C is spelled
_Bool
. You can use that without including any header.stdbool.h
simply defines the macros:as a convenience.
hmm interesting, should've checked the content of stdbool
On some level, you can. On another level, you're setting yourself up for pain by doing that.
The level where you can use a
char
variable is when it's only your code. All things considered, if you want to createchar
variables where each bit is a different boolean variable, you could do that. Again, it's your code.However, it's not that "we can use" integers. It's that the C standard library widely does use an integer as its returned status code. So, if you decide to manage your yes/no values in some other way, you need to yank the relevant bits out of that return value to fit it into your new scheme. So, that's potentially significant overhead. In fact, even if it's your own code, if you write
if (booleanInChar) { /* ...*/ }
, thatchar
variable is going to get "promoted" to anint
, because that's the type the conditional statement requires.But really, bytes are cheap. And, if you're not writing embedded code, you're probably not going to notice any memory savings, because your program is going to be loaded into a multi-megabyte memory segment to run, anyway. So, you're better off keeping it simple.
I see, yes I agree that simple code is better than clever code. Sometimes other users will find it weird or might not undertsand if we don't use the standard convention.
I think you can use char as a Boolean. '\0' will be treated as false and all other characters as true if I'm not mistaken.
isn't it easier to use
char false = 0;
?It would work as expected for most cases but I (personally) would prefer to avoid type conversion.