16

In C and C++, what is the advantage of making a local const variable static? Assuming the initialization does not use other variables, is there any difference between preserving the value between calls, and setting the same constant value each call?

Could a valid C compiler ignore the static?

In C++, it avoids the construction/destruction between calls, but could there be any other benefit?

Tor Klingberg
  • 4,790
  • 6
  • 41
  • 51
yukon
  • 409
  • 1
  • 5
  • 15

2 Answers2

9

It doesn't take up stack-space may be a benefit if you have something like:

static const double table[fairly_large_number] = { .... };

Obviously, cost of construction can also be substantial enough that if the function is called a lot, there's good value in only constructing the object once.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • Your point about taking up stack space makes sense, until you realize it must be initialized because it's `const`. Anything that you're willing to put into a source file as constants could probably fit on the stack easily. – Mark Ransom Feb 20 '13 at 23:58
  • Hmm, that's helpful. Another small question, is a volatile var likely be registered? – yukon Feb 20 '13 at 23:59
  • @MarkRansom: a) that would depend on the size of the stack, b) how many different things like this I've got. And whatever I do, the initializer list will be part of my code, either way. If it's, say, a machine generated table of constants for a Times Roman font that I want to have hard-coded in my word-processor, then that wouldn't be a good thing to put on the stack, even if the stack is quite large. I have actually written code that has LARGE tables in it, because that makes more sense than having code in the program to build the tables. – Mats Petersson Feb 21 '13 at 00:08
  • @Yukon, what do you mean by "registered"? Kept in a register, no, that would be invalid by the compiler, each access of a volatile variable must be done exactly as the code describes, can not be skipped or eliminated. – Mats Petersson Feb 21 '13 at 00:09
3

Yes, and it is huge: a semantic benefit.

When you put const, you don't just mean the compiler shouldn't let you modify the variable. You make a bolder statement to whoever reads the code later: this won't ever change. Not even by a side effect where you give this variable as a pointer to another function.

Also, the compiler can take advantage of that new information and optimize it away in some situations, depending on the specific type you are dealing with.

(to be clear, I'm speaking here about const vs. non-const, not static vs. non-static.)

Edit: This SO answer is very informative too.

Community
  • 1
  • 1
Qortex
  • 7,087
  • 3
  • 42
  • 59