5
\$\begingroup\$

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?

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ It would be less surprising to put false before true so that the members are listed in ascending order as usual in an enum. \$\endgroup\$ Mar 25 '14 at 8:44
  • \$\begingroup\$ My C++ instructor comes from Pascal, and would always require explicit casts... I guess it stuck. \$\endgroup\$
    – motoku
    Mar 25 '14 at 18:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.