C Booleans
In this page:
Booleans Before stdbool.h
Classic C has no dedicated boolean type -- conditions were always expressed with plain int, where the value 0 meant false and any non-zero value meant true, a convention that still underlies how every if and loop condition in C is evaluated today.
Example: Booleans Before stdbool.h
#include <stdio.h>
int main() {
int isValid = 1;
if (isValid) {
printf("True (non-zero)");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The bool Type from stdbool.h
Including <stdbool.h> brings in the bool type along with the true and false macros, which expand to 1 and 0 respectively -- it's a thin, readable layer over the same underlying integer representation, not a genuinely new machine type.
Example: The bool Type from stdbool.h
#include <stdio.h>
#include <stdbool.h>
int main() {
bool isReady = true;
printf("%d", isReady);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
What _Bool Actually Is
bool is itself just a macro for _Bool, the real keyword the C99 standard introduced -- _Bool is guaranteed to store only 0 or 1, so assigning any non-zero value to it, like 10, is automatically normalized down to 1.
Example: What _Bool Actually Is
#include <stdio.h>
int main() {
_Bool flag = 10;
printf("%d", flag);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using Booleans in Conditions
A bool variable can be used directly in an if or while condition without comparing it to true explicitly -- writing if (isValid) is clearer and more idiomatic than if (isValid == true), which is redundant and easy to get wrong if reversed by mistake.
Example: Using Booleans in Conditions
#include <stdio.h>
#include <stdbool.h>
int main() {
bool isValid = true;
if (isValid) {
printf("Valid");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Booleans as Function Return Values
Functions that answer a yes/no question read far more clearly when declared to return bool instead of int -- bool isPrime(int n) documents the function's intent at a glance, compared to an int-returning function where the meaning of 0 versus 1 has to be inferred.
Example: Booleans as Function Return Values
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
return n == 2 || n == 3 || n == 5 || n == 7;
}
int main() {
printf("%d", isPrime(5));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- C Introduction
- C History & Features
- C Environment Setup
- C First Program
- C Syntax & Structure
- C Statements
- C Comments
- C Keywords & Identifiers
- C Data Types
- C Character Data Type
- C Numeric Data Types
- C Decimal (Floating-Point) Numbers
- C sizeof Operator
- C Extended Data Types
- C Type Conversion
- C Booleans
- C Variables
- C Changing Variable Values
- C Multiple Variables
- C Constants
- C Fixed-Width Integers