Does static make a difference for a const local variable?

And is there any danger associated with any of these solutions?

Non-static is dangerous because the array is huge, and the memory reserved for automatic storage is limited. Depending on the system and configuration, that array could use about 30% of the space available for automatic storage. As such, it greatly increases the possibility of stack overflow.

While an optimiser might certainly avoid allocating memory on the stack, there are good reasons why you would want your non-optimised debug build to also not crash.


Forget the array for a moment. That muddles two separate issues. You've got answers that address the lifetime and storage issue. I'll address the initialization issue.

void f() {
    static const int x = get_x();
    // do something with x
}

void g() {
    const int x = get_x();
    // do something with x
}

The difference between these two is that the first one will only call get_x() the first time that f() is called; x retains that value through the remainder of the program. The second one will call get_x() each time that g() is called.

That matters if get_x() returns different values on subsequent calls:

int current_x = 0;
int get_x() { return current_x++; }