C ++ - static assignment during initialization

Say I have a C ++ function:

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

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

+5
source share
5 answers

Consider several different static variables:

 void foo(int x) { static int bar = x; static std::string s1 = "baz"; static std::string s2("baz"); static int i{2}; // C++11-style uniform initialization } 

Do you also think that s1 should "assign" a value of "baz" every time a function is called? What about s2 ? What about i ?

None of these statements perform any assignment, they are all initialized, and they are executed only once. Just because the operator includes the = symbol does not make it an assignment.

The reason the language is defined this way is because it usually uses a local static variable to run the function once:

 bool doInit() { // run some one-time-only initialization code // ... return true; } void func() { static bool init = doInit(); // ... } 

If init again assigned a value each time the function is called, then doInit() will be called several times and will not be able to use a one-time installation.

If you want to change the value every time he called, it's just ... just change it. But if you do not want it to continue to change, then there would be no way to do this if the language worked as you ask.

It would also be impossible to have a local variable static const :

 void func() { static const bool init = doInit(); // ... } 

Unfortunately, this will try to change the init value with every call.

0
source

This is not a "task." This is initialization. And, according to the rules of the C ++ language, static objects are initialized only once - when the control passes over the declaration for the first time.

In your example, the control goes over the bar declaration when x is 3 . So bar initialized 3 . It will never be “reinitialized”, i.e. Calling foo(4) will not affect bar at all. If after that you want to change the value of bar , you need to directly change bar .

+6
source

Short answer: because the standard says so.

The long answer: this is not an assignment, but initialization, and it is ignored because the standard talks about it.

+2
source

The memory location for bar not valid until the first foo call that appears when the bar . bar gets initialized to x when it is created. Each call to foo after, bar has already been created and, therefore, has already been initialized.

0
source

this is initialization of a static variable instead of assigning values ​​to it. in this case, the value of bar will always be equal to 3 if u calls foo (3) in the very first place.

0
source

Source: https://habr.com/ru/post/1200260/


All Articles