c++staticconstantslanguage-lawyerstorage-duration

Do all const objects have static storage duration?


I wonder if all constants in C++ have static duration, even though they are created inside a function other than main()?

For example:

const int a = 3;     

int main()
{
    const int b = 4;
}

What is the difference between a and b?


Solution

  • Whether an object is const and whether it has static storage duration are unrelated. An object defined inside a function has automatic storage duration unless explicitly marked static or thread_local. A static data member of a class has static storage duration unless explicitly marked thread_local. An object defined at namespace scope has static storage duration unless explicitly marked thread_local.