简体   繁体   中英

Why Declaration of static variable with non-constant does not give Error in g++

 int main ( )
 {
       int a = 1 ;
       static int b = a ;
 }

This piece of code gives error in gcc 4.3.2 as

error : initializer element is not constant.

But it runs fine on g++ 4.3.2 . Someone Please Explain why this is not giving error in g++ 4.3.2.

Because it is valid in C++ (and not valid in C).

(C++11, 6.7p4) "Constant initialization (3.6.2) of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. [...] Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM