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
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments