C语言
#include<malloc.h>
int a = 1;
int b,c;
b = 1;
c = a;
char *ch = (char * ) malloc (10);
int main(void)
{
return 0;
}
root@liujie-desktop:/software# gcc yan.c
yan.c:4: warning: data definition has no type or storage class
yan.c:5: warning: data definition has no type or storage class
yan.c:5: error: initializer element is not constant
yan.c:6: error: initializer element is not constant
全局变量(external variable)和静态变量 (static variable)的初始化式必须为常量表达式。
c99标准描述如下:
C99标准 6.7.8 Initialization 第4款:
4 All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
关于 static storage duration:
C99 6.2.4 Storage durations of objects 第3款:
3 An object whose identifier is declared with external or internal linkage, or with the
storage-class specifier static has static storage duration. Its lifetime is the entire
execution of the program and its stored value is initialized only once, prior to program startup.
C99标准 6.7.8 Initialization 第4款:
4 All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
关于 static storage duration:
C99 6.2.4 Storage durations of objects 第3款:
3 An object whose identifier is declared with external or internal linkage, or with the
storage-class specifier static has static storage duration. Its lifetime is the entire
execution of the program and its stored value is initialized only once, prior to program startup.
问题:全局变量c的值不能在编译时确定,要在执行是确定
C++语言
#include<malloc.h>
#include<stdio.h>
int a = 1;
int b,c;
c = a;
b = 2;
char *ch = (char *)malloc(sizeof(char)*10);
int main(void)
{
printf("ch = %p\n",ch);
return 0;
}
root@liujie-desktop:/software# g++ yan.cpp
yan.cpp:5: error: expected constructor, destructor, or type conversion before ‘=’ token
yan.cpp:6: error: expected constructor, destructor, or type conversion before ‘=’ token
本文探讨了C语言中全局变量及静态变量的初始化问题,并基于C99标准详细解释了为何这些变量的初始化表达式必须为常量表达式。同时对比了C++语言中的不同之处。

1万+

被折叠的 条评论
为什么被折叠?



