Typesafe enums in C?

后端 未结 6 587
我寻月下人不归
我寻月下人不归 2021-01-12 02:29

If I have more than one enum, eg:

 enum Greetings{ hello, bye, how };

 enum Testing { one, two, three };

How can I enforce th

6条回答
  •  -上瘾入骨i
    2021-01-12 02:47

    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.

提交回复
热议问题