← Back to C Course | Chapter 1: Introduction & Basics | Lesson 16 of 21

C Booleans

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

c
#include <stdio.h>
int main() {
	int isValid = 1;
	if (isValid) {
		printf("True (non-zero)");
	}
	return 0;
}

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

c
#include <stdio.h>
#include <stdbool.h>
int main() {
	bool isReady = true;
	printf("%d", isReady);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	_Bool flag = 10;
	printf("%d", flag);
	return 0;
}

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

c
#include <stdio.h>
#include <stdbool.h>
int main() {
	bool isValid = true;
	if (isValid) {
		printf("Valid");
	}
	return 0;
}

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

c
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.