Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a function local static variable automatically incur a branch?

Tags:

For example:

int foo() {     static int i = 0;     return i++; } 

The variable i will only be initialized to 0 the first time foo is called. Does this automatically mean there's a hidden branch in there to keep the initialization from happening more than once? Or are there more clever tricks to avoid this?

like image 429
Borgleader Avatar asked May 23 '14 12:05

Borgleader


People also ask

What happens when a local function variable is declared as static?

Static local variables: variables declared as static inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.

Are local variables automatic?

The term local variable is usually synonymous with automatic variable, since these are the same thing in many programming languages, but local is more general – most local variables are automatic local variables, but static local variables also exist, notably in C. For a static local variable, the allocation is static ...

How does a local static variable behave differently from a local variable in a function?

A static local variable is different from a local variable as a static local variable is initialized only once no matter how many times the function in which it resides is called and its value is retained and accessible through many calls to the function in which it is declared, e.g. to be used as a count variable.

Is initialisation mandatory for local static variables?

Is initialisation mandatory for local static variables? Explanation: None.


1 Answers

Yes, it must incur a branch, and it must also incur at least an atomic operation for safe concurrent initialization. The Standard requires that they are initialized on function entry, in a concurrency-safe way.

The implementation can only dodge this requirement if it can prove that the difference between lazy init and some earlier initialization like before main() is entered is equivalent. For example, simple PODs initialized from constants, the compiler may choose to initialize it earlier like a file-scope global since it's non-observable and saving the lazy initialization code, but that's a non-observable optimization.

like image 100
Puppy Avatar answered Sep 25 '22 17:09

Puppy