Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does static make a difference for a const local variable?

Tags:

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?

like image 278
bartop Avatar asked Mar 01 '19 10:03

bartop


People also ask

Can we use static with const?

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.

Are const variables static?

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.

Can local variable be static?

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.

What would happen if we declared a local variable as static local?

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.


2 Answers

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++; }
like image 124
Pete Becker Avatar answered Sep 21 '22 18:09

Pete Becker


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.

like image 40
eerorika Avatar answered Sep 19 '22 18:09

eerorika