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

后端 未结 17 1807
一生所求
一生所求 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:10

    Generally speaking:

    static const
    

    Because it respects scope and is type-safe.

    The only caveat I could see: if you want the variable to be possibly defined on the command line. There is still an alternative:

    #ifdef VAR // Very bad name, not long enough, too general, etc..
      static int const var = VAR;
    #else
      static int const var = 5; // default value
    #endif
    

    Whenever possible, instead of macros / ellipsis, use a type-safe alternative.

    If you really NEED to go with a macro (for example, you want __FILE__ or __LINE__), then you'd better name your macro VERY carefully: in its naming convention Boost recommends all upper-case, beginning by the name of the project (here BOOST_), while perusing the library you will notice this is (generally) followed by the name of the particular area (library) then with a meaningful name.

    It generally makes for lengthy names :)

提交回复
热议问题