If I have more than one enum
, eg:
enum Greetings{ hello, bye, how };
enum Testing { one, two, three };
How can I enforce th
Unfortunately enum
are a weak point in the type system of C. Variables of an enum
type are of that enum
type, but the constants that you declare with the enum
are of type int
.
So in your example
enum Greetings{ hello, bye, how };
enum Testing { one, two, three };
enum Greetings const holla = hello;
enum Testing const eins = one;
hello
and one
are two names for the same value, namely 0
, and with the same type int
.
holla
and eins
again have value 0
, but have their respective types.
If you want to force some "official" type safety for "real" constants, that is entities that have the type and value that you want, you'd have to use some more involved constructs:
#define GREETING(VAL) ((enum Greetings){ 0 } = (VAL))
#define HELLO GREETING(hello)
The assignment in the GREETING
macro ensures that the result is an "rvalue" so it can't be modified and will be taken by the compiler just for its type and value.