Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

 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.

like image 768
rforritz Avatar asked Jan 09 '13 19:01

rforritz


People also ask

Why static variables are initialized outside class?

That's because the static class member is stored separately rather than as part of an object. The exception to the initialization of a static data member inside the class declaration is if the static data member is a const of integral or enumeration type.

Why are static variables initialized to zero?

Yes, it's because it's in the standard; but really, it's because it's free. Static variables look just like global variables to the generated object code.

Why static variables are initialized only once?

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name.

Are static variables initialized to zero?

3) Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage.


1 Answers

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."

like image 165
ouah Avatar answered Oct 21 '22 14:10

ouah