Variable Storage Classes
Automatic: auto
- storage is automatically allocated on function/block entry and automatically freed when the function/block is exited
- may not be used with global variables (which have storage space that exists for the life of the program)
auto
is the default for function/block variablesauto int a
is the same asint a
- because it is the default, it is almost never used
Optimization Hint: register
register
provides a hint to the compiler that you think a variable will be frequently used- compiler is free to ignore
register
hint - if ignored, the variable is equivalent to an
auto
variable with the exception that you may not take the address of aregister
(since, if put in a register, the variable will not have an address) - rarely used, since any modern compiler will do a better job of optimization than most programmers
Static Storage: static
-
if used inside a block or function, the compiler will create space for the variable which lasts for the life of the program(生命周期为整个程序运行期)
-
int counter(void) { static int cnt = 0; return cnt++; }
causes the
counter()
function to return a constantly increasing number
External References: extern
-
If a variable is declared (with global scope) in one file but referenced in another, the
extern
keyword is used to inform the compiler of the variable’s existence:-
In
declare.c
:int farvar;
-
In
use.c
:{ extern int farvar; int a; a = farvar * 2; }
-
-
Note that the
extern
keyword is for declarations, not definitions- An
extern
declaration does not create any storage; that must be done with a global definition(extern变量的声明不会被分配内存空间,必须在其他文件中进行定义)
- An
Private Variables: static
-
another use for the
static
keyword is to ensure that code outside this file cannot modify variables that are globally declared inside this file(static变量拥有文件作用域)-
If
declare.c
had declaredfarvar
as:static int farvar; // 文件作用域,只对declare.c可见
then the
extern int farvar // 对于use.c不可见
statement in
use.c
would cause an error -
This use of
static
is commonly used in situations where a group of functions need to share information but do not want to risk other functions changing their internal variablesstatic int do_ping = 1; /* start with `PING' */ void ping(void) { if (do_ping == 1) { printf("PING "); do_ping = 0; } } void pong(void) { if (do_ping == 0) { printf("PONG\n"); do_ping = 1; } }
-
Variable Initialization
-
auto
,register
andstatic
variables may be initialized at creation:int main(void) { int a = 0; register int start = 1234; static float pi = 3.141593; }
-
Any global and
static
variables which have not been explicitly initialized by the programmer are set to zero -
If an
auto
orregister
variable has not been explicitly initialized, it contains whatever was previously stored in the space that is allocated to it- this means that
auto
andregister
variables should always be initialized before being used(特别注意) - compiler may provide a switch to warn about uninitialized variables
- this means that