What is the difference between static const and const?

CStaticConstants

C Problem Overview


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?

C Solutions


Solution 1 - C

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.

Solution 2 - C

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.

Solution 3 - C

It depends on whether these definitions are inside of a function or not. The answer for the case outside a function is given by ouah, above. Inside of a function the effect is different, illustrated by the example below:

#include <stdlib.h>

void my_function() {
  const int foo = rand();         // Perfectly OK!
  static const int bar = rand();  // Compile time error.
}

If you want a local variable to be "really constant," you have to define it not just "const" but "static const".

Solution 4 - C

const int i=5;  

i value you can modify by using a pointer if i is defined and declared locally, if it is static const int a=5; or const int i=5; globally , you can not modify since it is stored in RO memory in Data Segment.

    #include <stdio.h>
   //const int  a=10;              /* can not modify */
   int main(void) {
   // your code goes here

   //static const int const a=10;   /* can not modify */
   const int  a=10; 
   int *const ptr=&a;
   *ptr=18;
   printf("The val a is %d",a);
   return 0;
} 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLiorView Question on Stackoverflow
Solution 1 - CJoeView Answer on Stackoverflow
Solution 2 - CouahView Answer on Stackoverflow
Solution 3 - CnibotView Answer on Stackoverflow
Solution 4 - CTobinView Answer on Stackoverflow