What is boolean in C?

A boolean is a data type in the C Standard Library which can store true or false. Every non-zero value corresponds to true while 0 corresponds to false.

The boolean works as it does in C++. However, if you don’t include the header filestdbool.h, the program will not compile.

svg viewer

Another option is to define our own data type using typedef, which takes the values true and false:

typedef enum {false, true} bool;

However, it is safer to rely on the standard boolean in stdbool.h.

Examples


1. Using the header file stdbool.h

#include <stdio.h>
#include <stdbool.h>
int main() {
bool x = false;
if(x){
printf("x is true.");
}
else{
printf("x is false.");
}
}

2. Using typedef

#include <stdio.h>
typedef enum {false, true} bool;
int main() {
bool x = false;
if(x){
printf("x is true.");
}
else{
printf("x is false.");
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved