Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Use of bool in C
In C, there is no predefined datatype as bool. However, we can create a boolean type using enum or use the standard <stdbool.h> header (C99 and later). With enum, we create a boolean type where false holds value 0 and true holds value 1.
Syntax
typedef enum { false, true } bool;
// Or using C99 standard
#include <stdbool.h>
Method 1: Using Enum
We can create a custom boolean type using typedef enum −
#include <stdio.h>
typedef enum {
false, true
} bool;
int main() {
bool my_bool1, my_bool2;
my_bool1 = false;
if(my_bool1 == false) {
printf("my_bool1 is false
");
} else {
printf("my_bool1 is true
");
}
my_bool2 = true;
if(my_bool2 == false) {
printf("my_bool2 is false
");
} else {
printf("my_bool2 is true
");
}
printf("false = %d, true = %d
", false, true);
return 0;
}
my_bool1 is false my_bool2 is true false = 0, true = 1
Method 2: Using stdbool.h (C99+)
Modern C provides <stdbool.h> header which defines bool, true, and false −
#include <stdio.h>
#include <stdbool.h>
int main() {
bool is_valid = true;
bool is_complete = false;
printf("is_valid: %s
", is_valid ? "true" : "false");
printf("is_complete: %s
", is_complete ? "true" : "false");
/* Boolean operations */
bool result = is_valid && !is_complete;
printf("is_valid AND NOT is_complete: %s
", result ? "true" : "false");
return 0;
}
is_valid: true is_complete: false is_valid AND NOT is_complete: true
Key Points
- In enum method,
falsegets value 0 andtruegets value 1 automatically. - The
<stdbool.h>approach is standard and preferred in modern C. - Both methods allow boolean logic operations like
&&,||, and!.
Conclusion
C supports boolean types through custom enum or the standard <stdbool.h> header. The standard approach using <stdbool.h> is recommended for modern C programming as it provides better compatibility and readability.
Advertisements
