Reputation: 269
My question is in the foo()
function, the sa
variable seems to be declared and initialized there, however since it is static is it ignored by the compiler after the first time? How come it is not initialized back to the value 10 even if it's static?
#include <stdio.h>
void foo()
{
int a = 10;
static int sa = 10;
a += 5;
sa += 5;
printf("a = %d, sa = %d\n", a, sa);
}
int main()
{
int i;
for (i = 0; i < 10; ++i)
foo();
}
This prints:
a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
Upvotes: 1
Views: 62
Reputation: 8861
Your program would work identically if you declared sa
globally, though its scope would be different:
int sa = 10;
void foo()
{
int a = 10;
a += 5;
sa += 5;
printf("a = %d, sa = %d\n", a, sa);
}
The reason you might want to declare sa
within foo
is to limit its access.
Upvotes: 1
Reputation: 123598
Objects with static
storage duration are allocated and initialized once at program startup, and that storage is held until the program terminates.
Thus, the sa
variable is allocated and initialized when the program starts, not when foo
is first executed, and it persists between calls to foo
.
The sa
variable is only visible by name within the foo
function, however.
Upvotes: 0
Reputation: 13085
static
can declare a function which is only visible within the compilation unit.
This use of static
variables within a function,
a) reserves a piece of memory which will hold the single value (irrespective of threads), and
b) Initialize it only once. In C++11
this is guaranteed to be thread safe, although I don't think there is such a guarantee in C
.
So there is a single piece of memory reserved. Until the function is called, it will not be setup
Upvotes: 0
Reputation: 134396
Quoting C11
standard, chapter §6.2.4, Storage durations of objects
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 specifierstatic
, 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, sa
is not being initialized on every call. It is initialized only once and holds the last stored value.
That said, regarding the retention of the value, quoting the same spec,
[..] An object exists, has a constant address, and retains its last-stored value throughout its lifetime. [...]
The reason of putting it inside a function is to limit the scope of the variable to that function scope itself.
Upvotes: 2
Reputation: 49920
In C, static
means that it persists between calls, so it is the opposite of what you suggest: the initialization only occurs on the first call.
Upvotes: 2