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 #define
d 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...