In C:
there are 2 different uses of the keyword static- Static function declarations
- Static ads out of scope
(MOST) EVIL: static variables in a function
A static variable in a function is used as the state of "memory".
Basically, your variable is initialized to the default value only the first time you call it, and then saves its previous value in all future calls.
, , , : .
, EVIL/ BAD.
:
#include <stdio.h>
void ping() {
static int counter = 0;
return (++counter);
}
int main(int ac, char **av) {
print("%d\n", ping());
print("%d\n", ping());
return (0);
}
:
1
2
() :
static (, , ).
, , , . . , /var "" , , , , " ".
, .
, GOOD.
:
example.h
#ifndef __EXAMPLE_H__
# define __EXAMPLE_H__
void function_in_other_file(void);
#endif
file1.c
#include <stdio.h>
#include "example.h"
static void test(void);
void test(void) {
printf("file1.c: test()\n");
}
int main(int ac, char **av) {
test();
function_in_other_file();
return (0);
}
file2.c
#include <stdio.h>
#include "example.h"
static void test(void);
void test(void) {
printf("file2.c: test()\n");
}
void function_in_other_file(void) {
test();
return (0);
}
:
file1.c: test()
file2.c: test()
PS: , : , , , , " " ( ) C. .