Hi I'm studying for my test in C and i've encountered a question which i can't figure its answer.
A programmer wrote a program to count number of users (Count.h, Count.c):
/******** FILE: Counter.h ***********/
static int counter = 0;
int getUsersNum ();
/******** END OF FILE: Counter.h ****/
/******** FILE: Counter.c ***********/
#include "Counter.h"
int getUsersNum ()
{
return counter;
}
/******** END OF FILE: Counter.c ****/
And a tester to test it:
/******** FILE: CounterMain.c ***********/
#include "Counter.h"
#include <stdio.h>
int main ()
{
int i;
for (i=0;i<5;++i)
{
++counter;
printf ("Users num: %d\n", getUsersNum());
}
return 0;
}
/******** END OF FILE: CounterMain.c ****/
Suprisingly the output was:
Users num: 0
Users num: 0
Users num: 0
Users num: 0
Users num: 0
I can't see why with this use of static variable the counter does not advance.. why did they get such input?
thank you all!
In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program.
static int is a variable storing integer values which is declared static. If we declare a variable as static, it exists till the end of the program once initialized.
In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory.
The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).
In C, the scope of a static variable is the source file in which its defined.
Since you're loading this header into 2 separate .c files, each file gets a unique variable. Incrementing "counter" in one file does not affect the "static" variable in the other file.
For details, see this description. In order for the variable to be visible and shared in multiple files, it needs to be declared as extern. Otherwise:
Static global variables: variables declared as static at the top level of a source file (outside any function definitions) are visible throughout that file ("file scope").
Which is the case here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With