initializer element is not constant

来源:互联网 发布:怎样申请做淘宝模特 编辑:程序博客网 时间:2024/06/01 10:05

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.cyan.c:4: warning: data definition has no type or storage classyan.c:5: warning: data definition has no type or storage classyan.c:5: error: initializer element is not constantyan.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<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.cppyan.cpp:5: error: expected constructor, destructor, or type conversion before ‘=’ tokenyan.cpp:6: error: expected constructor, destructor, or type conversion before ‘=’ token



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