Post by Andrey TarasevichPost by Jackconstexpr size_t N = 12;
#define N 12
constexpr is modern way of doing things but in terms of efficiency what
is the best way to do?
There's no difference in efficiency.
One can probably come up with a few reasons to prefer a macro for this
purpose, like
1. Compatibility with C in cross-compiled header files
"enum { N = 12 };" also works if you need compatibility with C in
headers. And if you are on C23, then "constexpr size_t N = 12;" is fine
in C too.
You can also write "static const size_t N = 12;" and use it in a fair
number of circumstances, though not as many as with a constexpr or
macro. You can use it for local variable array sizes in C and C++, but
not for a file-scope array in C.
Post by Andrey Tarasevich2. Ability to use a named constant in subsequent preprocessor directives
(e.g. `#if`)
"if constexpr" and templates can provide alternatives to using #if, and
work with constexpr values. But conditional preprocessor may be simpler
and clearer, depending on the context and usage.
Post by Andrey Tarasevich3. Probably something else...
Two things come to mind for "#define N 12" :
3a. You can later on write :
#undef N
#define N 42
3b. You can write :
#ifndef N
#define N 100
#endif
These make #define's nice for things like configuration files where you
might have defaults that you want to override. Template variables,
including template constexpr variables, can be an alternative.
Post by Andrey TarasevichBut these reasons are focused rather narrowly of some niche
applications. When you _have_ a choice, there's no reason to avoid
`constexpr`.
Agreed. A key point is that constexpr variables (like other variables)
follow scoping rules, and can be put in namespaces or inside classes.