Static int in function

I came across this code:

void function(int nextFoo) { static int lastFoo = nextFoo; if (nextFoo != lastFoo) { // is this possible? } lastFoo = nextFoo; } 

The encoder believes that lastFoo is only installed on the first run, and the last line is it right? I think (but don’t know) that the code in the if block never runs, but cannot find confirmation of this.

+6
source share
5 answers

The encoder believes that nextFoo is only installed on the first run, and the last line is it right?

Yes. static local variables are initialized only once (and not every time a function is introduced). In C ++ 11, this is also guaranteed in thread safe mode. For paragraph 6.7 / 4 of the C ++ 11 standard:

[...] If the control enters the declaration at the same time when the variable is initialized, simultaneous execution should wait for the initialization to complete [...]

Note that if the initialization of the static object throws an exception, its initialization will be retried the next time function() entered (in this case, it does not matter, since the initialization of int cannot throw). From the same paragraph above:

[...] If initialization is completed by throwing an exception, the initialization is not complete, so it will be checked again the next time the control enters the declaration. [...]

+17
source

Of course it is possible. Static initialization occurs only once . The next time you call the function, initialization is no longer performed.

(In fact, initialization even without a race :-).)

+4
source

The code in the block can work; the following example prints hello :

 #include <iostream> using namespace std; void function(int nextFoo) { static int lastFoo=nextFoo; if (nextFoo!=lastFoo) { cout << "hello" << endl; } lastFoo=nextFoo; } int main() { function(1); function(2); return 0; } 
+3
source

Simple answer: yes lastFoo will only be installed here:

 static int lastFoo=nextFoo; 

but that would be enough to test how it works for you. Of course, the final destination will be set at the end of the lastFoo function:

 #include <iostream> void function(int nextFoo) { static int lastFoo=nextFoo; std::cout << "lastFoo: " << lastFoo << std::endl ; if (nextFoo!=lastFoo) { std::cout << "here" << std::endl ; } lastFoo=nextFoo; } int main() { function(10) ; function(11) ; } 
+1
source

Static is a storage class and tells the compiler that a variable is not an automatic variable that is created / destroyed every time a function is introduced and left.

From the K & RC programming language (2nd edition)

A4.1 Storage Class

There are two storage classes: automatic and static

...

Static objects can be local to a block or external to all blocks, but in any case they retain their values ​​for output and return to functions and blocks.

So, the if completely legitimate. When calling a function, a variable may have a different value.

0
source

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


All Articles