Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the default initialization values of static variables in c++ objects?

I believe that all numerical variables are initialized to zero, but what about things like static bool or static MyClass*?

I have looked around the interwebs, but most results I found are for how to initialize things like ints to non-zero values, and I just want to know the defaults.

like image 988
Stack Tracer Avatar asked Jul 30 '14 17:07

Stack Tracer


People also ask

What are the default value of static variables in C?

The default initialization value of a static variable is zero, even if it is not assigned, which is not the case in a local variable. It is mandatory to initialize the static variable using the static keyword in C else it will return an error.

When static variables are initialized in C?

A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence. A static object of class type will use the default constructor if you do not initialize it.

Is static variable initialized by default?

Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code.

Are static variables initialized to 0?

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

Global variables, local static variables, and static member variables are all zero initialized, unless otherwise initialized. This means floating point values are zero, booleans are false, pointers are nullptr etc

See http://en.cppreference.com/w/cpp/language/zero_initialization

like image 147
Some programmer dude Avatar answered Sep 28 '22 00:09

Some programmer dude