CS157 Static
static
The keyword static
has several meanings in C:
static
local variable endures—keeps its value.
static
global variable is private to the file containing it.
static
function is private to the file containing it.
int get_id_number() { int id=1000000; return ++id; } int main() { printf("First id: %d\n", get_id_number()); printf("Second id: %d\n", get_id_number()); printf("Third id: %d\n", get_id_number()); return 0; }
First id: 1000001 Second id: 1000001 Third id: 1000001
That doesn’t work very well.
int id=1000000; int get_id_number() { return ++id; } int main() { printf("First id: %d\n", get_id_number()); printf("Second id: %d\n", get_id_number()); printf("Third id: %d\n", get_id_number()); return 0; }
First id: 1000001 Second id: 1000002 Third id: 1000003
That’s ok, but global variables are evil.
static
local variableint get_id_number() { static int id=1000000; return ++id; } int main() { printf("First id: %d\n", get_id_number()); printf("Second id: %d\n", get_id_number()); printf("Third id: %d\n", get_id_number()); return 0; }
First id: 1000001 Second id: 1000002 Third id: 1000003
It works, and has no global variables!
static
global varaiblesint value; // global void save(int n) { value = n; } int recall() { return value; } int main() { save(42); printf("That value was: %d\n", recall()); return 0; }
That value was: 42
It works if our whole program is in one file. If one file has a
global int value
and another has a global double value
, then
we’re in trouble.
static
global varaiblesstatic int value; // static global void save(int n) { value = n; } int recall() { return value; } int main() { save(42); printf("That value was: %d\n", recall()); return 0; }
That value was: 42
value
is now private to this file. It doesn’t interfere with
anything in other files.
static
functionsvoid foo() { puts("Hello from foo"); } void bar() { foo(); } int main() { bar(); return 0; }
Hello from foo
Consider a multi-file program. You might want bar
to be visible
to the other files, but not foo
. Too bad—they’re both visible!
static
functionsstatic void foo() { puts("Hello from foo"); } void bar() { foo(); } int main() { bar(); return 0; }
Hello from foo
Hooray! foo
is now local to this file. It can’t be see from other
files. Another file could have its own foo
, and they won’t
interfere.
static
mainstatic int main() { puts("Hello, world!"); return 0; }
c.c:1: warning: 'main' is normally a non-static function c.c:1: warning: 'main' defined but not used /usr/lib/gcc/x86_64-redhat-linux/8/../../../../lib64/crt1.o: In function `_start': (.text+0x24): undefined reference to `main' collect2: error: ld returned 1 exit status
Don’t do this. main
has to be visible, so that it can be called
by whoever calls main
to kick things off.
Modified: 2016-11-30T15:22 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |