I noticed that most of the predefined values in libc
are written using #define
directives. For example, the whence
parameter takes an int
in fseek
where (from my knowledge) an enum
would have been better. There are plenty of examples like this that should obviously exist for a reason (other than back-compatibility issues).
So I am wondering in which case is it better to use #define
whereas enum
is a type-safe alternative more easily discoverable.
As a practical example consider a typedef
representing an input/output channel, as it could be the case on the kernel. The gpio can be configured either in input or output. Is it worth to use an enum
directive here?
typedef struct gpio {
size_t port;
size_t bit;
enum { DIR_INPUT, DIR_OUTPUT } direction; // or `bool`?
bool value;
} gpio;
Notice that the enum
can be implemented in three different manners:
i) Type:
typedef enum gpio_direction {
DIR_OUTPUT
DIR_INPUT
} gpio_direction;
ii) Global enum
enum gpio_direction {
DIR_OUTPUT
DIR_INPUT
} gpio_direction;
iii) Anonymous enum (as showed in my example).