Use of bool in C

Prerequisite: Bool Data Type in C++
The C99 standard for C language supports bool variables. Unlike C++, where no header file is needed to use bool, a header file “stdbool.h” must be included to use bool in C. If we save the below program as .c, it will not compile, but if we save it as .cpp, it will work fine.  

C

filter_none

edit
close

play_arrow

link
brightness_4
code

int main()
{
  bool arr[2] = {true, false};
  return 0;
}

chevron_right


If we include the header file “stdbool.h” in the above program, it will work fine as a C program. 

C

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdbool.h>
int main()
{
    bool arr[2] = { true, false };
    return 0;
}

chevron_right


There is one more way to do it using enum function in C language. You can create a bool using enum. One enum will be created as bool, then put the elements of enum as True and False respectively. The false will be at the first position, so it will hold 0, and true will be at the second position, so it will get value 1.

Below is the implementation of the above idea:

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// C implementation of the above idea
#include <stdio.h>
  
// Declaration of enum
typedef enum { F, T } boolean;
  
int main()
{
    boolean bool1, bool2;
    bool1 = F;
  
    if (bool1 == F) {
        printf("bool1 is false\n");
    }
    else {
        printf("bool1 is true\n");
    }
    bool2 = 2;
    if (bool2 == F) {
        printf("bool2 is false\n");
    }
    else {
        printf("bool2 is true\n");
    }
}

chevron_right


Output

bool1 is false
bool2 is true

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Improved By : pulkitagarwal03pulkit

Article Tags :
Practice Tags :


41


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.