C has a concept of 'Storage classes' which are used to define the scope (visability) and life time of variables and/or functions.
So what Storage Classes are available?
auto | register | static | extern | typedef |
{ int Count; auto int Month; }The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.
{ register int Miles; }Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implimentation restrictions.
static int Count; int Road; { printf("%d\n", Road); }static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.
'static' can also be defined within a function! If this is done the variable is initalised at run time but is not reinitalized when the function is called. This is serious stuff - tread with care.
{ static Count=1; }Here is an example
There is one very important use for 'static'. Consider this bit of code.
char *func(void); main() { char *Text1; Text1 = func(); } char *func(void) { char Text2[10]="martin"; return(Text2); }Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify
static char Text[10]="martin";The storage assigned to 'text2' will remain reserved for the duration if the program.
Source 1 | Source 2 |
---|---|
extern int count; int count=5; write() main() { { printf("count is %d\n", count); write(); } } |
test |
The compile command will look something like.
gcc source1.c source2.c -o program
Top | Master Index | Keywords | Functions |