What is the difference between static const
and const
? For example:
static const int a=5; const int i=5;
Is there any difference between them? When would you use one over the other?
They mean exactly the same thing. You're free to choose whichever you think is easier to read. In C, you should place static at the start, but it's not yet required.
“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.
The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object's entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable.
static
determines visibility outside of a function or a variables lifespan inside. So it has nothing to do with const
per se.
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.
Technically (if you want to look this up), static
is a storage specifier and const
is a type qualifier.
The difference is the linkage.
// At file scope static const int a=5; // internal linkage const int i=5; // external linkage
If the i
object is not used outside the translation unit where it is defined, you should declare it with the static
specifier.
This enables the compiler to (potentially) perform further optimizations and informs the reader that the object is not used outside its translation unit.
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