This is one way to make a boolean in C.
typedef enum {
false = 1 == 0,
true = 0 == 0
} bool;
Recently I made some like
typedef enum {
true = ~(int)0, //true is the opposite of false
false = (int)0 //the smallest enum is equal to sizeof int
} bool;
int main(void) {
return false;
}
Can this be improved upon?
1 Answer 1
Well, according to the ANSI book:
The identifiers in an enumerator list are declared as constants of type
int
So the cast is redundant:
typedef enum {
true = ~0,
false = 0
} bool;
Also, in C, a "true" value is anything other than zero, so ~0
is no more "true" than 1
- might as well keep it simple:
typedef enum {
false = 0,
true = 1
} bool;
In fact, 0
and 1
are the standard choice for representing boolean values where there's no native boolean type (for example, the bit
type in SQL uses 0
/1
).
Now you might ask yourself, "so - did we just redefine zero and one?" - well, we certainly did. As an experiment in using typedef
/enum
it's okay. But don't use it in actual C code, because it'll make if
clauses unnecessarily complex.
For example, let's say we want to compare str
and str2
and to do something if they're not equal. We'll use strcmp
which compares two strings and returns 0 if they're equal.
// without bool
if(strcmp(str1,str2))
{
...
}
// with bool
if(strcmp(str1,str2) == 0 ? false : true)
{
...
}
In conclusion, as an experiment your code is OK and can be slightly improved. Generally, the lack of bool
type in C seems scary at first, but it's actually quite convenient when you get used to it.
-
\$\begingroup\$ It would be less surprising to put
false
beforetrue
so that the members are listed in ascending order as usual in anenum
. \$\endgroup\$200_success– 200_success2014年03月25日 08:44:21 +00:00Commented Mar 25, 2014 at 8:44 -
\$\begingroup\$ My C++ instructor comes from Pascal, and would always require explicit casts... I guess it stuck. \$\endgroup\$motoku– motoku2014年03月25日 18:47:39 +00:00Commented Mar 25, 2014 at 18:47