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.