In C++ you can do this
enum class Colors {black, blue, green, cyan, red, purple, yellow, white};
Colors mycolor;
mycolor = Colors::blue; // this is what I want to do
In C
, is it possible to refer to an enum using EnumName::tag
?
In C++ you can do this
enum class Colors {black, blue, green, cyan, red, purple, yellow, white};
Colors mycolor;
mycolor = Colors::blue; // this is what I want to do
In C
, is it possible to refer to an enum using EnumName::tag
?
In C, is it possible to refer to an enum using EnumName::tag?
No, it is not. Read C11 standard, e.g. n1570 draft (§6.7.2.2)
In practice, C programmers have a lot of conventions, such as using some common prefix for all the tags in some enum
.
For example in GTK all the tags of enum GtkShadowType
start with GTK_SHADOW_
(a common prefix, by human convention), like GTK_SHADOW_IN
and GTK_SHADOW_OUT
. This makes the C code more readable for developers, since GTK has a lot of enum
s.
In some cases, you may generate C code (with software like SWIG or GNU bison or your own one). Then your C code generator should also document and adopt such naming conventions for generated C code (in particular, to help the human developer recognize easily generated C names from hand-written ones).
In large software (e.g. the Linux kernel), it is important to document naming and coding conventions. This facilitates the job of future developers.
Good source code editors (e.g. GNU emacs) can be configured to type long identifiers with few key presses, and current C optimizing compilers spend much more time in optimization than in parsing, so after 2020 having long but readable identifiers is important in large software code bases (and that does not impact significantly the compilation time, or the runtime).
Don't forget that with care, you can mix C and C++ code, and make a library coded in C++ which has a C interface and API. The libgccjit is a good example (with it, you can embed an optimizing GCC compiler -it is coded in C++- in your application, which would construct some abstract syntax tree). Be careful about C++ exceptions: all of them should be caught before returning from your library.