Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid name collisions with enum in C (C99)

enum elements' names are susceptible to overlap/collide with both other enum elements names, variable names, etc...

enum Fruit
{
    apple,
    orange
};
typedef enum Fruit Fruit;


enum Color
{
    red,
    orange // <-- ERROR
};
typedef enum Color Color;


char apple='a'; // <-- ERROR

Is there a C99 compliant solution to avoid collision other than prefixing every enum element name?


Side note: this question has already an answer for C++

How to avoid name conflicts for two enum values with the same name in C++?

I'm looking for a C99 solution.

like image 726
Paolo Avatar asked Feb 13 '16 13:02

Paolo


People also ask

Can two enums have the same name?

No two enum members can have the same name. Each enum member has an associated constant value.

What is the point of enums in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.


1 Answers

In C, there is no solution other than prefixing the names of the enum values.

As pointed out in the OP, C++ has a number of mechanisms, of which enum class is probably indicated for modern code. However, in practice the result is the same: you end up prefixing the name of the enum element with the name of the enum. Arguably, Fruit::orange is tidier than FruitOrange, but really it makes little difference to my eyes.

In some parallel universe, it would be great to have a language in which you could write:

Fruit selected = orange;

and have the compiler deduce the namespace of the constant on the right-hand side. But I don't see how that language could be C. C doesn't have namespaces in that sense, and even if it did, the type system only allows conversions; you cannot condition the syntax of the RHS of an operator based on the LHS (and I use the word syntax deliberately, because name lookup is a syntactic property in C).

Even if you did have some language hack which sometimes implictly inserted an enum namespace, you would still need the explicit prefix on any comparison, because

if (apple > orange)

does not have a context in which deduction could take place, even though the fact that enum values in C are all of type int does make FruitApple and FruitOrange comparable.

like image 80
rici Avatar answered Oct 23 '22 16:10

rici