What is true and what is false?
In C, the concepts of true and false are represented using integers. The integer value 0 is considered false, and any non-zero value is considered true. However, C99 introduced the <stdbool.h>
header, which defines the _Bool
type and introduces the bool
type and the constants true
and false
. Here are examples using both approaches:
Using integers:
#include <stdio.h>
int main() {
// Using integers
int trueValue = 1;
int falseValue = 0;
if (trueValue) {
printf("This statement is true\n");
} else {
printf("This statement is false\n");
}
if (falseValue) {
printf("This statement is true\n");
} else {
printf("This statement is false\n");
}
return 0;
}
In this example, the conditions inside the if
statements are evaluated based on the truthiness or falsiness of the integer values.
Using <stdbool.h>
:
#include <stdio.h>
#include <stdbool.h>
int main() {
// Using <stdbool.h>
bool trueValue = true;
bool falseValue = false;
if (trueValue) {
printf("This statement is true\n");
} else {
printf("This statement is false\n");
}
if (falseValue) {
printf("This statement is true\n");
} else {
printf("This statement is false\n");
}
return 0;
}
Here, the <stdbool.h>
header is included, and the bool
type is used with true
and false
constants. This makes the code more readable and expressive.
Both examples will produce the same output:
This statement is true
This statement is false
In C, it's common to see the integer approach, especially in older codebases. However, using bool
from <stdbool.h>
provides better readability and is preferred in modern C programming.