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.
color_orange
andfruit_orange
. It should also avoid the confusion when reading. – CrawlerFruit f = orange;
andColor c = orange;
? It's tidy and no doubt thanf
is a fruit andc
a color – ThaliaFruit fruit = FruitOrange;
. Oh and in this caseswitch (fruit) {case FruitOrange: break ...}
. If there are many fruits you will be glad to prefix them. Alsof
can be forfile
,f**ck
, and many other wrods that start withf
fruit
instead is simplyfruit
. – CrawlerFuirt f = orange;
is ugly, why not make itFruit f = o;
too and shorten it more to make it prettier? – Crawlerf
is a letter. Why do you assumef
must always stand for a word? Sometimes verbosity is pointless within context, more difficult to read, and leads to typos as you already mixed up "Fuirt" with "Fruit." When you start down the path of "do this thing because I was told it is good," you often end up in a mire, as is evidenced by the appalling state of software "development" we see these days; where all the code runs slower, is harder to read, harder to maintain, and with more bugs every year. A million 4-line, verbose functions in a half-million 2-function files. Yuck! – Stairhead