Is it reasonable to use enums instead of #defines for compile-time constants in C?

后端 未结 7 879
刺人心
刺人心 2021-02-05 09:19

I\'m coming back to some C development after working in C++ for a while. I\'ve gotten it into my head that macros should be avoided when not necessary in favor of making the com

7条回答
  •  [愿得一人]
    2021-02-05 09:57

    A const int MY_CONSTANT = 7; will take up storage; an enum or #define does not.

    With a #define you can use any (integer) value, for example #define IO_PORT 0xb3

    With an enum you let the compiler assign the numbers, which can be a lot easier if the values don't matter that much:

    enum {
       MENU_CHOICE_START = 1,
       MENU_CHOICE_NEXT,
       ...
    };
    

提交回复
热议问题