Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Static Assignment in Initialization

Tags:

c++

static

Say I have a C++ function:

void foo(int x) {
    static int bar = x;
}

If I call foo(3) then afterwards call foo(4), it is my understanding that the value of bar will still be 3. Why is this? I understand why the memory allocation part of the initialization is redundant. but why is the assignment also ignored?

like image 386
Dan Brenner Avatar asked Aug 13 '14 18:08

Dan Brenner


2 Answers

It is not an "assignment". It is an initialization. And, per rules of C++ language, initialization of static objects is performed only once - when the control passes over the declaration for the very first time.

In your example, the control passes over the declaration of bar when x is 3. So, bar is initialized with 3. It will never be "reinitialized", i.e. calling foo(4) will not affect bar at all. If you want to change the value of bar after that, you have to modify bar directly.

like image 68
AnT Avatar answered Oct 08 '22 19:10

AnT


Short answer: because the standard says so.

Long answer: that's not an assignment, but an initialisation, and it's ignored because the standard says so.

like image 42
Lightness Races in Orbit Avatar answered Oct 08 '22 19:10

Lightness Races in Orbit