请向我解释如何在 C 中全局初始化变量范围以及静态和外部之间的区别
变量的作用域意味着:它在哪里可以被看到(也就是它在哪里存在),从而可以被访问。
变量的范围取决于它在代码中的定义位置。
变量在函数外部定义时获得全局作用域。关键字static
可以限制全局变量的范围,以便它只能在特定的 c 文件(又名编译单元)中看到。所以:
文件1.c
int gInt1; // Global variable that can be seen by all c-files
static int gInt2; // Global variable that can be seen only by this c-file
void foo(void)
{
int lInt; // Local variable
...
}
为了使用另一个 c 文件中的全局变量,您告诉编译器它存在于某个其他文件中。为此,您使用extern
关键字。
文件2.c
extern int gInt1; // Now gInt1 can be used in this file
void bar(void)
{
int n = gInt1 * (gInt1 + 1);
...
}
您经常将extern
声明放入头文件中。像:
文件1.h
extern int gInt1; // Any c-file that includes file1.h can use gInt1
文件2.c
#include "file1.h" // Now gInt1 can be used in this file
void bar(void)
{
int n = gInt1 * (gInt1 + 1);
...
}
关于初始化
初始化全局变量与初始化局部变量没有区别。
全局变量和局部变量之间的唯一区别是没有初始化程序。在这种情况下,局部变量将保持未初始化,而全局变量将默认初始化(这通常意味着初始化为零)。
文件1.c
int gInt1 = 42; // Global variable explicit initialized to 42
int gInt2; // Global variable default initialized to 0
void foo(void)
{
int lInt1 = 42; // Local variable explicit initialized to 42
int lInt2; // Local variable uninitialized. Value is ??
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句