Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use boolean datatype in C?

Tags:

c

types

boolean

I was just writing code in C and it turns out it doesn't have a boolean/bool datatype. Is there any C library which I can include to give me the ability to return a boolean/bool datatype?

like image 540
itsaboutcode Avatar asked Nov 11 '10 22:11

itsaboutcode


People also ask

How do Booleans work in C?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

Can we use bool data type in C?

In C there is no predefined datatype as bool. We can create bool using enum. One enum will be created as bool, then put the false, and true as the element of the enum. The false will be at the first position, so it will hold 0, and true will be at second position, so it will get value 1.

What is boolean value in C?

In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool type value represents two types of behavior, either true or false. Here, '0' represents false value, while '1' represents true value. In C Boolean, '0' is stored as 0, and another integer is stored as 1.

Why is there no boolean in C?

C is a very close-to-the-metal language, and abstracting true/false into a new data type that is not reflective of something that hardware can uniquely understand didn't make much sense (a bool would simply be a char with additional limitations, simple enough to typedef yourself if you really need it).


2 Answers

If you have a compiler that supports C99 you can

#include <stdbool.h> 

Otherwise, you can define your own if you'd like. Depending on how you want to use it (and whether you want to be able to compile your code as C++), your implementation could be as simple as:

#define bool int #define true 1 #define false 0 

In my opinion, though, you may as well just use int and use zero to mean false and nonzero to mean true. That's how it's usually done in C.

like image 121
James McNellis Avatar answered Oct 02 '22 12:10

James McNellis


C99 has a boolean datatype, actually, but if you must use older versions, just define a type:

typedef enum {false=0, true=1} bool; 
like image 26
caveman Avatar answered Oct 02 '22 13:10

caveman