DEV Community

Clavin June
Clavin June

Posted on

Boolean in C

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?

Top comments (8)

Collapse
 
pgradot profile image
Pierre Gradot

Oh come on... C has a (very basic) bool type since C99:

#include <stdbool.h>
#include <stdio.h>

int main(void) {
    bool a = true;
    bool b = false;

    if (a && !b) puts("hello, bool in C99");    
}
Enter fullscreen mode Exit fullscreen mode

; )

Collapse
 
pauljlucas profile image
Paul J. Lucas

No, the actual Boolean type in C is spelled _Bool. You can use that without including any header. stdbool.h simply defines the macros:

#define bool _Bool
#define false 0
#define true 1
Enter fullscreen mode Exit fullscreen mode

as a convenience.

Collapse
 
clavinjune profile image
Clavin June

hmm interesting, should've checked the content of stdbool

Collapse
 
jcolag profile image
John Colagioia (he/him)

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 create char 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) { /* ...*/ }, that char variable is going to get "promoted" to an int, 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.

Collapse
 
clavinjune profile image
Clavin June

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.

Collapse
 
rinkiyakedad profile image
Arsh Sharma

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.

Collapse
 
clavinjune profile image
Clavin June

isn't it easier to use char false = 0;?

Collapse
 
rinkiyakedad profile image
Arsh Sharma

It would work as expected for most cases but I (personally) would prefer to avoid type conversion.