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?
-
4Usually a plain old 'int' is used, with the assumption that 0 is 'false' and anything else is 'true'.Rooke– Rooke2010-11-11 22:09:04 +00:00Commented Nov 11, 2010 at 22:09
-
Possible duplicate of Is bool a native C type?Jim Fell– Jim Fell2017-06-07 14:45:57 +00:00Commented Jun 7, 2017 at 14:45
7 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.
5 Comments
true and false are both macros that are replaced by 1 and 0, respectively, and bool is a macro that expands to the boolean type, _Bool.bool, true, and false, then make your return type bool and return false. Otherwise, just make your return type int and return 0. It's up to you waht you want to do. I just think the non-macro approach is better.C99 has a boolean datatype, actually, but if you must use older versions, just define a type:
typedef enum {false=0, true=1} bool;
1 Comment
bool pre-C99 is dangerous because the semantics differ. (bool)2 yields 2, not 1. A more realistic example: 1U<<(bool)isdigit(c) will give the wrong result on most implementations.As an alternative to James McNellis answer, I always try to use enumeration for the bool type instead of macros: typedef enum bool {false=0; true=1;} bool;. It is safer b/c it lets the compiler do type checking and eliminates macro expansion races
7 Comments
bool b = 1;#define bool int.float f; f = true; should raise a warning for the implicit (and supposedly incompatible) type cast.