在C语言数据存储类型关键字中有一个static,static有三种链接类型(linkage type),即static with no linkage, static with internal linkage 以及 static with external linkage。我在一本书上,即C Primer Plus ,看到对static with no linkage的描述,如下:
Static, no linkage— A variable declared in a block with the static storage class modifier belongs to the "static, no linkage" storage class. It has static storage duration, block scope, and no linkage. It is initialized just once, at compile time. If not initialized explicitly, its bytes are set to 0.
按照这样的对“static, no linkage”的定义,则具有该存储类型的变量就只具有“block linkage”,即它只在一个程序段中起作用,言下之意就是在程序的其他地方不起作用。
而稍后我又在该书的练习题中发现这样的一个问题:
Which storage classes create variables that persist for the duration of the containing program?
译文:何种存储类型能够产生出变量,该变量能够在其所处的程序范围内持续存在?
给出的参考答案是:
The static, no linkage storage class, the static, internal linkage storage class, and the static, external linkage storage class.
译文:静态,无链接存储类型、静态,内部链接存储类型以及静态,外部链接类型
按照这样的参考答案,也就是说static no linkage类型的变量不只可以在其所处的程序段范围内存在还可以持续在整个程序范围内存在了?这和前面提出的static, no linkage类型的定义不矛盾吗?而且我做了一个测试程序(如下)也证明定义是正确的而这个练习问题的参考答案不正确。
/* experimenting with static and auto */
#include <stdio.h>
int main(void){
int a = 5;
int b = 4;
if(a > b){
static int c = a; //这里c = a 这个表达式也非法,c不能被赋予非常量值
int d = b;
printf("\nc = %d, d = %d, c - d = %d\n",
c,d,c-d);
}
//printf("\nc = %d, d = %d\n"c,d); 这里c、d已经不为编译器所识别了
getch();
return 0;
}
谢谢!
The lifetime of an object is the portion of program execution during which storage is
guaranteed to be reserved for it. An object exists, has a constant address,25) and retains
its last-stored value throughout its lifetime.26) If an object is referred to outside of its
lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when
the object it points to reaches the end of its lifetime.