c - static variables -
can explain when static variables should used , why?
there 2 distinct uses of static
keyword in c:
- static declarations in function's scope
- static declarations outside of function's scope
(mostly) evil: static variables in function
a static variable in function used "memory" state.
basically, variable initialized default value first time call it, , retains previous value in future calls.
it potentially useful if need remember such state, use of such statics frowned upon because pretty global variables in disguise: consume memory until termination of process once.
so, in general, making localized functions evil / bad.
example:
#include <stdio.h> void ping() { static int counter = 0; return (++counter); } int main(int ac, char **av) { print("%d\n", ping()); // outputs 1 print("%d\n", ping()); // outputs 2 return (0); }
output:
1 2
(mostly) good: static variables outside of function's scope
you can use static outside of function on variable or function (which, after all, sort of variable , points memory address).
what limit use of variable file containing it. cannot call somewhere else. while still means that function/var "global" in sense consumes memory until program's termination, @ least has decency not pollute "namespace".
this interesting because way can have small utility functions identical names in different files of project.
so, in general, making localized functions good.
example:
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(); // calls test function declared above (prints "file1.c: test()") function_in_other_file(); return (0); }
file2.c
#include <stdio.h> #include "example.h" static void test(void); // that's different test!! void test(void) { printf("file2.c: test()\n"); } void function_in_other_file(void) { test(); // prints file2.c: test() return (0); }
output:
file1.c: test() file2.c: test()
ps: don't start throwing stones @ me if you're purist: know static vars not evil, they're not globals either, functions not variables, , there's no actual "namespace" (don't started on symbols) in c. that's sake of explanation here.
Comments
Post a Comment