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

后端 未结 7 880
刺人心
刺人心 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 10:05

    The advantage of using enum { FOO=34 }; over #define FOO 34 is that macros are preprocessed, so in principle the compiler don't really see them (in practice, the compiler does see them; recent GCC has a sophisticated infrastructure to give from what macro expansion some internal abstract syntax tree is coming).

    In particular, the debugger is much more likely to know about FOO from enum { FOO=34 }; than from #define FOO 34 (but again, this is not always true in practice; sometimes, the debugger is clever enough to be able to expand macros...).

    Because of that, I prefer enum { FOO=34 }; over #define FOO 34

    And there is also a typing advantage. I could get more warnings from the compiler using enum color_en { WHITE, BLACK }; enum color_en color; than using bool isblack;

    BTW, static const int FOO=37; is usually known by the debugger but the compiler might optimize it (so that no memory location is used for it; it might be just an immediate operand inside some instruction in the machine code).

提交回复
热议问题