Close, but not quite.
What modern versions of C++ have done is add a kind of meta-coding capability to the language, which is to say, you can write code for the
compiler to execute,
before your program ever runs.
The key is to remember that there are two distinct processes that code can target:
• code the generated executable runs
• code the compiler runs
This second possibility occurred because people playing around with templates quickly discovered that you can make the compiler do a lot of things that we previously would only do in the final, generated executable. Constexpr simply takes that to the next,
official level.
A nice example of using template meta-programming to compute a value
during compilation can be found here:
http://www.cplusplus.com/forum/general/59883/2/#msg326710
(program to compute the number of digits from 1 to N).
──────────────────────────────
There is no such thing as a constexpr variable (which is a nice oxymoron, thanks!).
The
value computed at any one step in a constexpr may be further modified until the final value is computed and written to the executable. Again, to the simplest possible example:
constexpr int x = 2 * 5 - 3;
is computed in (at least) two steps: (2 * 5) → 10, then (10 - 3) → 7. That intermediate value (the ‘10’) must be preserved somewhere during the computation, most likely in a register value, but not necessarily. It is also possible the compiler stores the result of the subtraction in yet another place in computer memory, but it is again more likely that the compiler simply replaces the 10 value with the new sum. The underlying code might even be expressed as something like:
constexprs['x'] = 2;
constexprs['x'] *= 5;
constexprs['x'] -= 3;
Next, when the compiler finds your code
using the constexpr value:
cout << x << "\n";
It can lookup the
x
in its table of constexpr values and perform a substitution:
cout << 7 << "\n";
and compile
that into your program’s executable.
──────────────────────────────
That is
different than creating a variable used by your program’s final executable:
int x = 2 * 5 - 3;
In this case, the compiler must still compute the value of the expression
2 * 5 - 3
. (And, while this computation
could be done by your executable, C and C++ compilers, at least, will do it for you so that no time is spent doing it when your executable runs.) Performing the proper computation and substitution:
int x = 7;
While your code is running,
x
is still a variable like any other, which your executable may modify and use at its leisure.
──────────────────────────────
As a final note, the simple examples I have been using (without the
constexpr
keyword) aren’t technically constexprs. They are what is called “constant folding”. The concept of
when code is evaluated/executed/computed between the two are the same, though, so we can safely ignore the differences in this context. Just be aware, however, that I have blurred some lines.
Hope this helps.