overshadow
overshadow

Reputation: 988

Does modern c++ will have default initialized value

I am new to c++ and I want to learn best practice of c++. I got one question, does the modern c++ compiler will auto assign default value for an uninitialized variable? If yes, does it mean that we do not need to assign default value to a variable or it depends on system?

Thank you for your help and clarification.

Upvotes: 0

Views: 189

Answers (3)

paulm
paulm

Reputation: 5892

With regard to what the compiler will do I think its more of the inverse, for example:

int x; // still must be inited, will contain random data
if (some_func())
{
   // some devs will do this for "performance" - i.e don't assign a value to x
   x = 2;
}

But if you write:

int x = 0;
if (some_func())
{
   x = 2;
}

The compiler will optimize this to:

int x;
if (some_func())
{
   x = 2; // Yes this code is actually the first example again :)
}

Assuming x is not used else where in the function.

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106244

Only static and global data is always initialised...

int w; // will be 0
static int x; // will be 0

void f() { static int x; /* will be 0 the first time this scope's entered */ }

struct S
{
    int n_;
};

S s_;  // s_.n_ will be 0 as s_ is global

int main()
{
    S s;  // s.n_ will be uninitialised
          // undefined behaviour to read before setting
}

For any other variables they must have - at some level in the code - explicit initialisation before they're read from. That might not be visible at the point a variable is declared though - it could be in a default constructor or an assignment. You can also cause initialisation like this:

int x{};  // will be 0
int* p = new int{};  // *p will be 0 

Upvotes: 4

Laura Maftei
Laura Maftei

Reputation: 1863

Default initialization is performed in three situations:
1) when a variable with automatic, static, or thread-local storage duration is declared with no initializer.
2) when an object with dynamic storage duration is created by a new-expression with no initializer or when an object is created by a new-expression with the initializer consisting of an empty pair of parentheses (until C++03).
3) when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.

More information here: http://en.cppreference.com/w/cpp/language/default_initialization

Upvotes: 1

Related Questions