initializer element is not constant

C语言

#include
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.

问题:全局变量c的值不能在编译时确定,要在执行是确定

C++语言

#include
#include
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/C++)