Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typesafe enums in C?

Tags:

c

enums

If I have more than one enum, eg:

 enum Greetings{ hello, bye, how };

 enum Testing { one, two, three };

How can I enforce the usage of the correct enum? For example, I don't want someone to use hello when they should be using one for better debugging and readability.

like image 233
drum Avatar asked Feb 11 '13 22:02

drum


1 Answers

In C, you can fake it with boilerplate code.

typedef enum { HELLO_E, GOODBYE_E } greetings_t;
struct greetings { greetings_t greetings; };
#define HELLO ((struct greetings){HELLO_E})
#define GOODBYE ((struct greetings){GOODBYE_E})

typedef enum { ONE_E, TWO_E } number_t;
struct number { number_t number; };
#define ONE ((struct number){ONE_E})
#define TWO ((struct number){TWO_E})

void takes_greeting(struct greetings g);
void takes_number(struct number n);

void test()
{
    takes_greeting(HELLO);
    takes_number(ONE);

    takes_greeting(TWO);
    takes_number(GOODBYE);
}

This should not incur any overhead, and produces errors instead of warnings:

$ gcc -c -std=c99 -Wall -Wextra test2.c
test2.c: In function ‘test’:
test2.c:19: error: incompatible type for argument 1 of ‘takes_greeting’
test2.c:20: error: incompatible type for argument 1 of ‘takes_number’

Notice that I'm not using GNU extensions, and no spurious warnings are generated. Only errors. Also note that I'm using a version of GCC that's as old as dirt,

$ gcc --version
powerpc-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5493)
Copyright (C) 2005 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

This should work with any compiler with support for C99's compound literals.

like image 108
Dietrich Epp Avatar answered Nov 06 '22 15:11

Dietrich Epp