Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between static const and const?

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?

like image 226
Lior Avatar asked Nov 01 '12 21:11

Lior


People also ask

Is it static const or const static?

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.

What do static and const mean?

“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.

What is the difference between static final and const?

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.


2 Answers

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.

like image 168
Joe Avatar answered Sep 20 '22 09:09

Joe


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.

like image 20
ouah Avatar answered Sep 18 '22 09:09

ouah