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