C C++全局變量初始化 initializer element is not constant 錯誤 c++中爲什麼不能對全局變量在函數外賦值

今天師弟的一個問題

//錯誤代碼

node *p;

p = new node;

int main(void)

{…}

//修改後

node *p = new node;

int main(void)

{…}

找了好久不知道什麼錯誤,我雖然很快幫他修改正確了,但卻不明白其實質

查了好久,可能有點專牛角尖,是關於c c++全局變量賦值的問題,同時也關係到初始化和賦值的關係等

http://topic.csdn.net/u/20090129/19/d8661d27-4790-46cb-a424-c4fc8f7e28b4.html
這個帖子討論了下c語言中全局變量的初始化
//test.c
char * p1 = (char *) malloc(10);  //出現 initializer element is not constant錯誤
int main(void)
{
  ...
}
這個的原因已經弄明白,應該是C標準沒有弄清楚,在c99中指明全局變量和static變量的初始化式必須爲常量表達式,因此類似這樣的情況也是有錯誤(VC和gcc下測試)
//test.c
int a = 1;
int b = a;
int main(void)
{
  ....
}
或者

//test.c
int main(void)
{
    int a = 1;
    static int b = a;
}

出現的錯誤都是initializer element is not constant,即初始值不是常量
上面是c語言的

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.

關於複雜類型 (比如struct):
C99 6.5.2.5 Compound literals 第7款:
7 All the semantic rules and constraints for initializer lists in 6.7.8 are applicable to
compound literals.
(參考
http://bbs.chinaunix.net/viewthread.php?tid=1275329&extra=&page=5 帖子 問題類似)

在c++中,編譯器可能有所改進,上面的幾個問題基本已經沒有
可參考下這個帖子,關於全局變量初始化的:
http://blogold.chinaunix.net/u1/41728/showart_347212.html

c、c++全局變量的賦值要在函數內部進行!

看下面測試例子:

int a;

a = 10; //這裏是對全局變量進行賦值操作,是錯誤的

int main(void)

{

}

例如下面這個帖子:

http://topic.csdn.net/u/20100616/10/3823436c-f19c-40f0-9053-374f58c56d11.html 

類似這樣的情況也是不可以的:

printf(“hellow/n”);

int main(void)

{…}

總結下:

1、c語言中全局變量和static變量的初始化需要指定一個常量,不能是一個非常量的表達式;而在c++中是可以的

2、在操作c和c++全局變量時,只能對其採用初始化的方式,而不能採用賦值的方式,即可以

int a = 10; //錯誤

而不可以:

int a;

a = 10;

這應該是一個菜鳥級的問題,o(︶︿︶)o 自己還是太嫩了啊~~~

參考資料有:

http://blog.csdn.net/lychee007/archive/2010/04/08/5462764.aspx

http://topic.csdn.net/u/20091020/18/a8643fa1-6586-4a71-8518-95d88ec6b399.html

http://bbs.chinaunix.net/viewthread.php?tid=1275329&extra=&page=5

http://topic.csdn.net/u/20100616/10/3823436c-f19c-40f0-9053-374f58c56d11.html

http://blogold.chinaunix.net/u1/41728/showart_347212.html

http://webservices.ctocio.com.cn/net/405/9158905.shtml

http://www.cnblogs.com/chio/archive/2008/10/06/1305145.html

http://my.chinaunix.net/space.php?uid=25311153&do=blog&id=117951

http://zhidao.baidu.com/question/137062995

http://bbs.chinaunix.net/thread-1285396-1-1.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章