I know static variables maintain their values for the entire runtime of the program even between function calls. Given the code below, what would be the value of x printed considering that x is declared as static and was initialized to zero. How does the using_static function not assign zero to the variable x during each call to the function?
int using_static()
{
static int x;
x = 0;
x ;
return (x);
}
int main()
{
int i;
i = 0;
while (i < 5)
{
using_static();
i ;
}
printf("%i", using_static());
return (0);
}
CodePudding user response:
Your code sets the static variable x
that has a default value of 0 to 0 every time the function is called an increments it so it's value won't go above 1. static variables are always initialized with a value (Implicitly with 0 in your case). The correct code would be
int using_static() {
static int x = 0; // The value of x won't be reassigned to 0 on every call since it has static storage.
// Setting x = 0 here, after it's declaration would reassign it on every call and never allow it to go above 1.
x ; // Value becomes 1 on first call, 2 on second call and so on
return x;
}
The statement where the variable was declared as static
is the only one which doesn't reassign the variable each time the function containing it is executed.
CodePudding user response:
Got it. Static variables are auto initialized to zero. If need be, they can only be initialized during declaration.
so while the above code would give an output of 1, changing using_static() to
int using_static()
{
static int x = 0;
x ;
return (x);
}
would give an output of 6.
Thanks to all who answered.
CodePudding user response:
How does the using_static function not assign zero to the variable x during each call to the function?
You are mistaken. Each time when the function is called the variable x is explicitly assigned with the value 0 due to the assignment statement
int using_static()
{
static int x;
x = 0;
^^^^^^
x ;
return (x);
}
So the returned value of the function is always equal to 1.
It seems you mean initialization of the variable instead of its assignment.
If you will remove the statement
int using_static()
{
static int x;
x ;
return (x);
}
then the function will output sequentially
1 2 3 4 and so on
Initially the variable x
is zero initialized. The initialization occurs before the program startup and occurs only once.
From the C Standard (5.1.2 Execution environments)
All objects with static storage duration shall be initialized (set to their initial values) before program startup.
and (6.7.9 Initialization)
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
....
You can imagine the function like
int using_static()
{
goto L1;
static int x = 0;
L1: x = 0;
x ;
return (x);
}