What Is the Lifetime of a Static Variable in a C++ Function

What is the lifetime of a static variable in a C++ function?

The lifetime of function static variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.

Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.

Example

struct emitter {
string str;
emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
~emitter() { cout << "Destroyed " << str << endl; }
};

void foo(bool skip_first)
{
if (!skip_first)
static emitter a("in if");
static emitter b("in foo");
}

int main(int argc, char*[])
{
foo(argc != 2);
if (argc == 3)
foo(false);
}

Output:

C:>sample.exe

Created in foo

Destroyed in foo

C:>sample.exe 1

Created in if

Created in foo

Destroyed in foo

Destroyed in if

C:>sample.exe 1 2

Created in foo

Created in if

Destroyed in if

Destroyed in foo

[0] Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.

[1] C++98 section 3.6.3.1 [basic.start.term]

[2] In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.

What is the lifetime of class static variables in C++?

Exactly like regular static (global) variables.

Static variable inside of a function in C

There are two issues here, lifetime and scope.

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

What happens to initialization of static variable inside a function

Although the standard does not dictate how compilers must implement behavior, most compilers do a much less sophisticated thing: they place c into static memory segment, and tell the loader to place zero into c's address. This way f comes straight to pre-initialized c, and proceeds to printing and incrementing as if the declaration line where not there.

In C++ it optionally adds code to initialize c to static initialization function, which initializes all static variables. In this case, no call is required.

In essence, this amounts to c starting its lifetime before the first call to f. You can think of c's behavior as if it were a static variable outside f() with its visibility constrained to f()'s scope.

Do automatic variables have lifetime equal to that of a static variable (within the same block)?

Do automatic variables have lifetime equal to that of a static
variable (within the same block)?

Short answer - No, an object with automatic storage duration is limited to the block within which it is declared. An object with static storage duration remains valid for the life of the program. See C11 Standard - 6.2.4 Storage durations of objects

Now within the same block, from the standpoint of either object, both remain valid for the life of the block. The one with automatic storage duration will simply cease to be accessible after leaving the block while the one with static storage duration can be accessed elsewhere.

Static variable inside a function

Normally you don't need to deal with concepts like "segment", it depends on the file format(ELF, Mach-O, etc.).

A static variable, no matter where it is defined, their lifetime and initialization rules are the same. The only difference is the visibility of this symbol to compiler and linker. In your particular example, static float c is also zero initialized, just as int a.

And technically, if you are dealing with linux and ELF format, static variable without explicit initialization is put in .bss segment, not .data segment. .bss segment has no physical size in the file, but will be zero-initialized when the ELF file is loaded to execute.

You can use nm command to see the symbols in your file if you are interested in.

Basic c question - What exactly happens when you declare a static variable in c?

Quoting C11, chapter §6.2.4, Storage durations of objects (emphasis mine)

An object whose identifier is declared without the storage-class specifier
_Thread_local, and either with external or internal linkage or with the storage-class
specifier static, has static storage duration. Its lifetime is the entire execution of the
program and its stored value is initialized only once, prior to program startup.

So, the initialization inside the function call does not take place on every call to the function. It only happens once, before the execution of main() starts. The variable retains the last stored value through the program execution, i.e, the value is retained between the repeated calls to the function.

how does a static variable not get reassigned when inside the function

Actually static variables can get reassigned. But can't be redefined.

Once a static variable defined it can't get redefined throughout the life time of program. But we can change the value.

The scope and lifetime of static local variable in c++

Scope is limited means any attempt to access x directly outside the scope is forbidden.

Within a scope, unqualified name lookup can be used to associate the
name with its declaration.

But you can always return a pointer or reference to this variable if variable is alive and you change it through that reference or pointer which points to the same variable. The name of this reference may be anonymous (temporary) or may be bound to some named reference.

About lifetime, it starts when the function containing static variable is called first time and ends when the program end.



Related Topics



Leave a reply



Submit