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.
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.
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.
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.
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.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With