Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a static variable in c

Tags:

c

static

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!

like image 662
Asher Saban Avatar asked Oct 03 '10 17:10

Asher Saban


People also ask

What are static variables?

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.

What is static int in C?

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.

Why do we use static in C?

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.

Where are static variables stored C?

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).


1 Answers

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.

like image 144
Reed Copsey Avatar answered Oct 21 '22 19:10

Reed Copsey