Why have different ways of variable initialization in C++?

Viewed 329

Since the 2011 revision of C++ standards, variables can be initialized in three different ways given below.

int i = 0;
int i (0);
int i {0};

As far as I know all three different initializations have the same effect. If they all have the same effect, why not stick to one way of initialisation like the first one? Is there any special need to initialise variables by surrounding their initial values in () or {}?

3 Answers

The reason for not disallowing any of the three is to maintain backward compatibility.

There are tons of code, in production, that is written with each of the three ways. If the standards were to be changed, working code would need to be rewritten, causing costs and possibly bugs. Since the C++ committee is very serious about backward compatibility, we end up in this situation. It is still way better than other language like Python, where, from minor version to minor version, you need to rewrite code to format a string, or to loop from zero to ten.

If you have the choice, pick {0}, it's called uniform initialization for a reason :-)

It is an historical question. The first one is int i=0;. This one is from the early C language from the 1970's. Next first C++ versions introduced a function like initialization syntax which writes here int i(0);. But because of the most vexing parse ambiguities, the curly braces initialization was invented.

And for compatibility reasons, all those syntaxes are still valid...

int i = 0;
int i (0); //For backward compatibility
int i {0}; //Uniform Initialization

There is a difference in these 3 types of initializations.

int i = 2.2;
int i (2.2);
int i {2.2};

First, two will do the implicit conversion but int i {0}; will give you error/warning for parameter narrowing.

For details about initializer list check this video.

Related