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

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

    I would stick to using the features for their purpose.

    A symbolic parameter, taking a discrete value among a set of alternatives, should be represented as an enum member.

    A numerical parameter, such as array size or numerical tolerance, should be represented as a const variable. Unfortunately, C has no proper construct to declare a compile-time constant (like Pascal had), and I would tend to say that a defined symbol is equally acceptable. I now even unorthodoxically opt for defined symbols using the same casing scheme as other identifiers.

    The enumerations with explicitly assigned values, such as binary masks, are even more interesting. At the risk of looking picky, I would consider to use declared constants, like

    #define IdleMask 1
    #define WaitingMask 2
    #define BusyMask (IdleMask | WaitingMask)
    enum Modes { Idle= IdleMask, Waiting= WaitingMask, Busy= BusyMask };
    

    This said, I wouldn't care so much about easing the compiler's task when you see how easily they handle the monstrous pieces of code that they receive daily.

提交回复
热议问题