全局变量和静态变量被初始化为其默认值,因为它处于C或C ++标准中,并且可以在编译时自由地将其赋值为零。静态变量和全局变量的行为与生成的目标代码相同。这些变量在.bss文件中分配,并且在加载时,它通过获取分配给变量的常量来分配内存。
以下是全局和静态变量的示例。
#include <stdio.h>
int a;
static int b;
int main() {
int x;
static int y;
int z = 28;
printf("The default value of global variable a : %d", a);
printf("\nThe default value of global static variable b : %d", b);
printf("\nThe default value of local variable x : %d", x);
printf("\nThe default value of local static variable y : %d", y);
printf("\nThe value of local variable z : %d", z);
return 0;
}输出结果
The default value of global variable a : 0 The default value of global static variable b : 0 The default value of local variable x : 0 The default value of local static variable y : 0 The value of local variable z : 28
在上述程序中,全局变量在main()函数外部声明,并且其中之一是静态变量。声明了三个局部变量,并且变量z也被初始化。
int a; static int b; …. int x; static int y; int z = 28;
将打印其默认值。
printf("The default value of global variable a : %d", a);
printf("\nThe default value of global static variable b : %d", b);
printf("\nThe default value of local variable x : %d", x);
printf("\nThe default value of local static variable y : %d", y);
printf("\nThe value of local variable z : %d", z);