HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Enumerating a boolean in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
enumeratingbooleanstackoverflow

Problem

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?

Solution

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.

Code Snippets

typedef enum {
    true = ~0,
    false = 0
} bool;
typedef enum {
    false = 0,
    true = 1
} bool;
// without bool
if(strcmp(str1,str2))
{
    ...
}

// with bool
if(strcmp(str1,str2) == 0 ? false : true)
{
    ...
}

Context

StackExchange Code Review Q#45284, answer score: 4

Revisions (0)

No revisions yet.