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?
“static const” is basically a combination of static(a storage specifier) and const(a type qualifier). The static determines the lifetime and visibility/accessibility of the variable.
When applied to a local variable, the static keyword defines the local variable as having static duration, meaning the variable will only be created once, and will not be destroyed until the end of the program.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.
const means that you're not changing the value after it has been initialised. static inside a function means the variable will exist before and after the function has executed. static outside of a function means that the scope of the symbol marked static is limited to that . c file and cannot be seen outside of it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With