Trusted answers to developer questions

What is boolean in C?

Checkout some of our related courses
Learn C from Scratch
Beginner
C++ Fundamentals for Professionals
Beginner
Coderust: Hacking the Coding Interview
Beginner

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.");
}
}

RELATED TAGS

boolean
c
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?