Does static make a difference for a const local variable?

  • A+
Category:Languages

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?

 


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++; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: