Originally, booleans did not have built-in support in C. With the advent of the C99 standard about ten years ago, C added a _Bool type. In this article, we’ll go over several ways that you can represent boolean values in C.
<stdheader.h>
Boolean logic can be implemented if you add the <stdheader.h>
header at the top of your file.
#include <stdio.h> #include <stdbool.h> int main() { bool value = 1; if(value){ printf("value is true."); } else{ printf("value is false."); } return 0; }
Using a header in C is analogous to creating a file of constants or functions in JavaScript that can be used across your project. The <stdbool.h>
header contains macros and constants for boolean values that can be used in your file.
typedef
A typedef
is a way to reassign a type to a new name:
typedef int bool;
Here the typedef
takes int and reassigns it to bool. Now we can use bool in our function:
#include <stdio.h> typedef int bool; enum { false, true }; int main() { bool value = 3; if(value){ printf("value is true."); } else{ printf("value is false."); } return 0; }
Typedef
defines types only. It is not used as a way to define constants or aliases. Enum defines the integral constants of true and false here. By default, enum values start at 0 and go up from there. If you’d like you can switch the default, but you don’t need to for this situation.
#define
The final way we will go over boolean logic is by using the #define keyword to create some boolean variables:
#include <stdio.h> typedef int bool; #define false 0 #define true 1 int main() { bool value = 3; if(value){ printf("value is true."); } else{ printf("value is false."); } return 0; }
As you can see, instead of using enum here, we are using #define to tell the compiler that false equates to 0 and true equates to 1 (which is in all honesty how the compiler sees these two values anyway).
Conclusion
In this article, we went over several ways to define bool values in C. Try your hand at learning something new in C that you already know how to do in another language!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.