3

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?

W.Joe
  • 335
  • 2
  • 8
  • what do you mean by static duration ? – Ratul Sharker Apr 15 '18 at 04:22
  • I know that string literals do, I've seen a question related to that. Don't know if that applies to other simple types but I suspect it does. It's actually a good question. – Mark Ransom Apr 15 '18 at 04:28
  • @MarkRansom Other kinds of literals (other than user-defined literals) do not occupy any memory in the abstract machine, and have no storage duration. – Brian Bi Apr 15 '18 at 04:30
  • If you're talking about constant variables instead of literals, no AFAIK. Why would it be like that? It's perfectly normal to have constant variables to not be initialized to compile-time constants. – eesiraed Apr 15 '18 at 04:33

2 Answers2

3

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.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • It is further useful to understand about static storage duration and thread storage duration: https://stackoverflow.com/questions/22794382/are-c11-thread-local-variables-automatically-static and https://en.cppreference.com/w/cpp/language/storage_duration – Hari Apr 25 '23 at 19:40
0

No; this is clearest if you create a const object with a constructor and destructor, which will be called when the program enters and leaves the scope in which the automatic const object is declared. The const automatic variable can also have different values on each invocation of the function, based on the parameters or other runtime data, while a static const local variable could not.

A constexpr object, however, cannot have non-trivial constructor or destructor or be initialized to anything but constants known at compile time, so it could be implemented the same way as a static variable.

Davislor
  • 14,674
  • 2
  • 34
  • 49