Objects have a storage duration that determines their lifetime. Altogether, four storage durations are available: automatic, static, thread, and allocated.
Automatic
Automatic storage duration occurs with an objects declared in a block of as a function parameter. The lifetime of these objects begins when they're declared and ends when execution of the block ends. If the block is entered recursively, a new object is created each time, each with its own storage.
Static
Objects declared in the file scope have static storage duration. The lifetime
of these objects is the entire execution of the program, and their stored value
is initialized prior to program startup. You can also declare a variable within
a block scope to have a static storage duration by using the class specifier
static
:
#include <stdio.h>
void increment(void)
{
static unsigned int counter = 0;
counter++;
printf("%d ", counter);
}
int main(void)
{
for (int i = 0; i < 5; i++) {
increment();
}
return 0;
}
As shown static variables can be modified during runtime, but will persist throughout the execution of the program. Whenever possible it's better to declare a static variable in the scope it will be used in rather than the file scope.
Static objects must be initialized with a constant value, not a variable.
Allocated
Thread
Used in concurrent programming. Bit more complex and I don't feel like writing about it now. Maybe just use go lol?