“static const” vs “#define” vs “enum”

后端 未结 17 1492
一生所求
一生所求 2020-11-21 05:45

Which one is better to use among the below statements in C?

static const int var = 5;

or

#define var 5

o

17条回答
  •  鱼传尺愫
    2020-11-21 06:09

    Incidentally, an alternative to #define, which provides proper scoping but behaves like a "real" constant, is "enum". For example:

    enum {number_ten = 10;}
    

    In many cases, it's useful to define enumerated types and create variables of those types; if that is done, debuggers may be able to display variables according to their enumeration name.

    One important caveat with doing that, however: in C++, enumerated types have limited compatibility with integers. For example, by default, one cannot perform arithmetic upon them. I find that to be a curious default behavior for enums; while it would have been nice to have a "strict enum" type, given the desire to have C++ generally compatible with C, I would think the default behavior of an "enum" type should be interchangeable with integers.

提交回复
热议问题