Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a static variable always use up memory?

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?

like image 320
Janick Bernet Avatar asked Dec 09 '22 05:12

Janick Bernet


1 Answers

So is the compiler allowed to optimize the static away[...] ?

Yes. According to the Standard:

1.9 Program Execution

The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.5)

...and the footnote says:

5) This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.

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.

like image 85
John Dibling Avatar answered Dec 11 '22 17:12

John Dibling