static const vs #define

前端 未结 11 960
醉话见心
醉话见心 2020-11-22 13:01

Is it better to use static const vars than #define preprocessor? Or maybe it depends on the context?

What are advantages/disadvantages for

11条回答
  •  攒了一身酷
    2020-11-22 13:23

    If this is a C++ question and it mentions #define as an alternative, then it is about "global" (i.e. file-scope) constants, not about class members. When it comes to such constants in C++ static const is redundant. In C++ const have internal linkage by default and there's no point in declaring them static. So it is really about const vs. #define.

    And, finally, in C++ const is preferable. At least because such constants are typed and scoped. There are simply no reasons to prefer #define over const, aside from few exceptions.

    String constants, BTW, are one example of such an exception. With #defined string constants one can use compile-time concatenation feature of C/C++ compilers, as in

    #define OUT_NAME "output"
    #define LOG_EXT ".log"
    #define TEXT_EXT ".txt"
    
    const char *const log_file_name = OUT_NAME LOG_EXT;
    const char *const text_file_name = OUT_NAME TEXT_EXT;
    

    P.S. Again, just in case, when someone mentions static const as an alternative to #define, it usually means that they are talking about C, not about C++. I wonder whether this question is tagged properly...

提交回复
热议问题