全局声明的变量被称为具有程序作用域
使用 static 关键字全局声明的变量被称为具有文件范围。
例如:
int x = 0; // **program scope**
static int y = 0; // **file scope**
static float z = 0.0; // **file scope**
int main()
{
int i; /* block scope */
/* .
.
.
*/
return 0;
}
这两者有什么区别?
最佳答案
不能从其他文件直接访问声明为 static
的变量。相反,如果在其他文件中声明为 extern
,则可以从其他文件访问非 static
。
例子:
foo.c
int foodata;
static int foodata_private;
void foo()
{
foodata = 1;
foodata_private = 2;
}
foo.h
void foo();
主.c
#include "foo.h"
#include <stdio.h>
int main()
{
extern int foodata; /* OK */
extern int foodata_private; /* error, won't compile */
foo();
printf("%d\n", foodata); /* OK */
return 0;
}
一般来说,应该避免使用全局变量。但是,在实际应用中,这些通常很有用。将 extern int foo;
声明移动到共享头文件(示例中的 foo.h)是很常见的。
关于c - "File scope"和 "program scope"有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14027317/