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

后端 未结 7 964
刺人心
刺人心 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:13

    Nowadays, in C++ there is no real good reason to use #define for compile-time constants. On the other hand, there are good reasons to use enums or enum classes instead. First and most important - they are much more readable during debugging.

    In C you may want to explicitly choose underlying type, which is impossible with enums. That might be a reason to use defines or consts. But enums should be strongly prefered.

    Runtime overhead is not a problem - in modern compilers there won't be any difference in generated machine code (as long as sizeof(the_enum)=sizeof(the_type_used_by_define_based_values)).

提交回复
热议问题