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!
Just think of it as “.h files don’t exist”. What happens is that the .h files are included inside the .c files and only the .c files get compiled (and linked (mixed) together).
In your case you have 2 .c files with
Each
counteris specific to the .c file it is in. Thecounterin CounterMain.c is a different variable than thecounterin Counter.c.You need to have one single definition of counter. You can have several declarations (typically in .h files)
Ohhhhhhhhhhhhhhhhhh and there’s the
staticthing. Don’t use it at global scope!