Static
The static
keyword is used for following
Hiding a Global Variable within a File Scope
imagine main.c
extern int var; // (1)!
int main () {
printf("%d", var);
}
extern
1 ensures thatprintf
usesvar
defined inside some other source file.
Imagine definition.c
static int var = 6; // (1)!
static
ensures that thevar
variable is only accessible insidedefinition.c
. Ifstatic
is removed, we will not get a linker error while trying to compile.
Attempting to compile will cause a linker error.
gcc main.c definition.c -o main.exe
main.c:(.rdata$.refptr.var[.refptr.var]+0x0): undefined reference to `var'
collect2.exe: error: ld returned 1 exit status
Static
Variables within Functions
2
void foo () {
static int var = 420;
var++;
printf("%d", var);
}
int main () {
foo(); // (1)!
foo(); // (2)!
}
- Since the declaration is encountered first time,
var
is created with value420
, incremented to421
and used. After thefunction
2 returns though, thevar
remains alive within memory. - Next time when
foo()
is called, the declaration ofvar
is skipped and the value421
(from previous call tofoo()
) is incremented to422
.