Based on this discussion, I was wondering if a function scope static variable always uses memory or if the compiler is allowed to optimize that away. To illustrate the question, assume a function like such:
void f() {
static const int i = 3;
int j = i + 1;
printf("%d", j);
}
The compiler will very likely inline the value of i
and probably do the calculation 3 + 1
at compile time, too. Since this is the only place the value of i
is used, there is no need for any static memory being allocated. So is the compiler allowed to optimize the static away, or does the standard mandate that any static variable has memory allocated?
Yes. According to the Standard:
1.9 Program Execution
...and the footnote says:
What this all means is that the compiler can do anything it wants to your code so long as the observable behavior is the same. Since you haven't take the address of the
static const
, the compiler can optimize the value away to a Constant Integral Expression.No, it will not always use memory. My GCC version 4.5.2 produces code with real global variable on
-O0
, but uses directly inline constant 4 when compiled with `-O3'According to section
1.8 The C++ object model
n3242An object has a type and a storage duration (optionally a name).
It does not require a memory location unless its address is taken.