But if you need access to the variable from all the functions in the entire source file, this can also done with the static keyword, but by putting the definition outside all functions. For example:
#include <stdio.h>
static int num = 10; /* will be accessible from entire source file */
int main(void)
{
printf("The Number Is: %d\n", num);
return 0;
}
And there are also cases where a variable needs to be accessible from the entire program, which may consist of several source files. This is called a global variable and should be avoided when it is not required.
This is also done by putting the definition outside all functions, but without using the static keyword:
#include <stdio.h>
int num = 10; /* will be accessible from entire program! */
int main(void)
{
printf("The Number Is: %d\n", num);
return 0;
}
There is also the extern keyword, which is used for accessing global variables in other modules. There are also a few qualifiers that you can add to variable definitions. The most important of them is const. A variable that is defined as const may not be modified.
There are two more modifiers that are less commonly used. The volatile and register modifier. The volatile modifier requires the compiler to actually access the variable every time it is read. It may not optimize the variable by putting it in a register or so. This is mainly used for multithreading and interrupt processing purposes etc.
The register modifier requests the compiler to optimize the variable into a register. This is only possible with auto variables and in many cases the compiler can better select the variables to optimize into registers, so this keyword is obsolescent. The only direct consequence of making a variable register is that its address cannot be taken.
The table of variables, given in the next page describes the storage class of five type of storage classes.
In the table we see the keyword extern is placed in two rows. The extern keyword is used in functions to declare a static external variable that is defined elsewhere.
Variable Storage class |
Defined as |
Scope |
Class |
Keyword |
Automatic |
Keyword is optional |
Temporary |
In a function |
Local |
Static |
static |
Temporary |
In a function |
Local |
Register |
register |
Temporary |
In a function |
Local |
External |
Optional |
Permanent |
Outside a function |
Global (all files) |
External |
Static |
Permanent |
Outside a function |
Global (one file) |
|