Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different kinds of variable initialization

Tags:

c++

What is the purpose of various type initialization in C++ and what is the correct one?

int i1 = 1;
int i2(1);
int i3{};
int i4 = {1};
int i5 = int{1};
like image 560
quantumbit Avatar asked May 11 '16 08:05

quantumbit


Video Answer


2 Answers

int i1 = 1;

This is good old C style. Still works fine and is conventional in C++.

int i2(1);

This is C++ style. It came about because some types need more than one argument to their constructor.

int i3{};

C++11 style.

int i4 = {1};

This is not conventional.

int i5 = int{1};

This is not conventional. But it's supported due to the new "uniform initialization syntax" of C++11.

int i6 = {};

You didn't ask about this one, but it's also valid in C++11.

int i7{1};

Another bonus, this is probably the most conventional use of uniform initialization syntax in C++11.

auto i8 = int{1};

Thanks to KerrekSB for this abomination, which he credits to none other than Herb Sutter. This will probably win you friends from the "No True Modern C++" camp, and alienate your coworkers who were perfectly happy with the first syntax.

like image 90
John Zwinck Avatar answered Sep 30 '22 19:09

John Zwinck


TL;DR - Use X a1 {v}; for initialization.

To take cue from Bjarne Stroustrup himself, below is directly quoted from TCPL, fourth edition -

If an initializer is specified for an object, that initializer determines the initial value of an object. An initializer can use one of four syntactic styles:

X a1 {v};
X a2 = {v};
X a3 = v;
X a4(v);

Of these, only the first can be used in every context, and I strongly recommend its use. It is clearer and less error-prone than the alternatives. However, the first form (used for a1) is new in C++11, so the other three forms are what you find in older code. The two forms using = are what you use in C.

like image 25
nightlytrails Avatar answered Sep 30 '22 20:09

nightlytrails