Meaning of default init and value init?

448 Views Asked by At

I am very confused by c++ ways of initializing variables. What is the difference if any, between these:

int i; // does this make i uninitialized?
int i{}; // does this make i = 0?
std::array<int, 3> a; // is a all zeros or all uninitialized?
std::array<int, 3> a{}; // same as above?

Thanks for clarifying

3

There are 3 best solutions below

0
Bo R On BEST ANSWER
int i; // does this make i uninitialized?

Yes, if in local scope and not in global scope.

int i{}; // does this make i = 0?

Yes, always.

std::array<int, 3> a; // is a all zeros or all uninitialized?

Uninitialized if in a local scope, but zeroed of in global scope, i.e., same as your first question.

std::array<int, 3> a{}; // same as above?

All values are default initizlized, i.e., all three elements are zeroed.

0
D-RAJ On

When you declare a variable and not initialize it with a value, it is uninitialized (it contains data that were previously stored in that address). It also depends on the scope and other factors to determine its initial value. {} used like in int i{}; calls its constructor which by default initializes the memory to its default value(s).

Its the same story for all the data structures (apart for the ones where the constructor is deleted).

0
foragerDev On

I would add to the previous answer, when you initialize variable like this {} it prevents narrowing of the type. For example

int x = 4.5 // It will narrowed to 4
int y{4.5}  //it will not compile