Imagine the following declaration:
void foo(){
const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}
And a second one:
void foo(){
static const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}
What are the possible performance differences between these two if any? And is there any danger associated with any of these solutions?
So combining static and const, we can say that when a variable is initialized using static const, it will retain its value till the execution of the program and also, it will not accept any change in its value.
The const variable is basically used for declaring a constant value that cannot be modified. A static keyword is been used to declare a variable or a method as static. A const keyword is been used to assign a constant or a fixed value to a variable.
Local Variables are variables inside a method. Only method gets to access these variables. you cannot have a static local variable , but you can use instance variables or class variables.
When applied to a local variable, the static keyword defines the local variable as having static duration, meaning the variable will only be created once, and will not be destroyed until the end of the program.
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++; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With