I always used #define
to define magic numbers somewhere at the beginning of the the cpp file. I want to change that to const
numbers. (globals declared / defined in the cpp file.) Is this a good idea? Should I put them into anonymous namespace? I never #include
the cpp files anywhere.
Basically the only reason you have for choosing such #define
"consts" is if the preprocessor itself will need to use them. Other than that, you have a whole heap of advantages for constexpr
over using such #define
s -- they are listed here.
Anonymous namespace are a good solution only if you're going to be using the magic numbers in the same file, as names inside it are never accessible from other translation units because the unnamed namespace has a unique identifier as far as the compiler is concerned. That said, There's no real gain here in putting the magic numbers inside an anonymous namespace, as either const
or constexpr
variables in any namespace scope inherently have internal linkage.
As far as the difference between const
and constexpr
goes in the context of objects, the gist is that while constexpr
denotes a constant value known during compilation, const
only denotes a constant value, that may not be known during compilation.1 This difference is crucial for compile-time programming, or for usage in other constant expressions.
1Do note that a const
integral that is itself being initialized with a constant expression (such as an integer literal) as part of its declaration is implicitly a constant expression even without explicitly declaring it constexpr
:
const int A = 50; // `A` is a constant expression
int n = 50;
const int B = n; // `B` is not a constant expression as it-
// is not being initialized with a constant expression