原创 C语言的两种存储类型

2010-6-15 21:07 2403 10 10 分类: 软件与OS


看谭浩强老师的书后一直以为C语言的存储类型(storage class)有四种(auto/static/register/external),今天看了《The C Programming Language·2nd Edition》后面所附的参考手册后,才发现以前的想法是错误的。根据这个手册对C89标准的解释,C语言的存储类型只有两种:动态的(automatic)和静态的(static)。

 

动态的变量是某个块的局部变量,当程序从这个块中退出时变量也自动撤销。如果没有特别声明(或者用auto关键字声明),变量默认是动态的。用关键字register声明的变量也是动态的,只是这个变量可能会被放在寄存器中。

 

静态的变量可能局部于某个块也可能扩展到所有块,无论是退出或重新进入某个程序块它的值都将保留。在程序块中,静态的变量用static声明。不在任何一个程序块内而和函数声明同级别的变量也是静态的。如果想使它们仅作用于某个特定的翻译单元(a particular translation unit)内(即文件范围),则用static声明,这样会使它们具有内在的联接(internal linkage);如果忽略存储类型或用external声明,则使它们具有外部的联接(external linkage),这样它们就具有全局作用域。

 

参考资料(摘自《The C Programming Language·2nd Edition》P195,北京,机械工业出版社,2006.8):

There are two storage classes: automatic and static. Several keywords, together with the context of an object's declaration, specify its storage class. Automatic objects are local to a block, and are discarded on exit from the block. Declarations within a block create automatic objects if no storage class specification is mentioned, or if the auto specifier is used. Objects declared register are automatic, and are (if possible) stored in fast registers of the machine.

 

Static objects may be local to a block or external to all blocks, but in either case retain their values across exit from and reentry to functions and blocks. Within a block, including a block that provides the code for a function, static objects are declared with the keyword static. The objects declared outside all blocks, at the same level as function definitions, are always static. They may be make local to a particular translation unit by use of the static keyword; this gives them internal linkage. They become global to an entire program by omitting an explicit storage class, or by using the keyord extern; this gives them external linkage.
PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
EE直播间
更多
我要评论
0
10
关闭 站长推荐上一条 /3 下一条