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

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

    is it reasonable to prefer using enums for constants rather than #define's ?

    If you like. Enums behave like integers.

    But I would still prefer constants, instead of both enums and macros. Constants provide type-safety, and they can be of any type. Enums can be only integers, and macros do not respect type safety.

    For example :

    const int MY_CONSTANT = 7;
    

    instead of

    #define MY_CONSTANT 7
    

    or

    enum
    {
      MY_CONSTANT = 7
    };
    

    BTW My answer was related to C++. I am not sure if it applies to C.

提交回复
热议问题