According to the C++23 standard, what is the output of this program?
#include <iostream>
int main() {
static int a;
std::cout << a;
}How are local static variables initialized?
0
Since a is a static local variable, it is automatically zero-initialized. This would not have happened if we removed the keyword static, making it a non-static local variable.
§[basic.start.static]¶2 in the standard:
If constant initialization is not performed, a variable with static storage duration (§[basic.stc.static]) or thread storage duration (§[basic.stc.thread]) is zero-initialized (§[dcl.init]).
a has static storage duration and is not constant-initialized , so it gets zero-initialized.
To zero-initialize an object or reference of type
Tmeans:— if
Tis a scalar type (§[basic.types.general]), the object is initialized to the value obtained by converting the integer literal0(zero) toT;
So a gets initialized to 0.