C语言:initializer element is not constant

来源:互联网 发布:java第一阶段测试题 编辑:程序博客网 时间:2024/05/22 15:35
static struct QueuePtr * header =( ( struct QueuePtr * ) malloc(sizeof(struct QueuePtr ) ) );
在编译时报错:initializer element is not constant 
原因:在c99中指明全局变量和static变量的初始化式必须为常量表达式
修改:
static struct QueuePtr * header = NULL;header = ( ( struct QueuePtr * ) malloc(sizeof(struct QueuePtr ) ) );


查阅其他博客,看到以下代码也会报同样的错误:
链接:为什么出现“initializer element is not constant”错误 
#include <stdio.h>  int a = 1;  int b = 2;  int c = a+b;    int main() {      printf("c is %d\n", c);      return 0;  }  
同理,上述代码中全局变量c的值是在执行时才确定的。全局变量的初始化是在编译阶段完成的,因此不可以是尚未确定其值的变量。


(1)c语言中全局变量和static变量的初始化需要指定一个常量,不能是一个非常量的表达式;
(2)作为全局变量,在编译之后就要确定它的地址,如果这个全局变量是个结构体的话,那么结构体里面的各个成员的具体值也要确定了。因为全局变量是存储在静态区,而只有常量表达式才可以前期确定值,而不是具体运行时确定值。
(3)依据:
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.

阅读全文
0 0
原创粉丝点击