1

In my header, I have these two public variables:

float testVariable1 = 1.23456789f;
float testVariable2{ 1.23456789f };

What's the difference here? Why have the version with the braces?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Jarryd
  • 572
  • 4
  • 13

2 Answers2

4

C++ supports three basic ways to initialize a variable. First, we can do copy initialization by using an equals sign:

int width = 5; // copy initialization of value 5 into variable width

This copies the value on the right-hand side of the equals to the variable being created on the left-hand side. Second, we can do a direct initialization by using parenthesis.

int width( 5 ); // direct initialization of value 5 into variable width

For simple data types (like integers), copy and direct initialization are essentially the same. But for some advanced types, direct initialization can perform better than copy initialization. Before C++11, direct initialization was recommended over copy initialization in most cases because of the performance boost.

Unfortunately, direct initialization can’t be used for all types of initialization. In an attempt to provide a more consistent initialization mechanism, C++11 added a new syntax for direct initialization called brace initialization (also called uniform initialization) that uses curly braces:

int width{ 5 }; // brace (uniform) initialization of value 5 into variable width

Hope this will help you.

Saurav Rai
  • 2,171
  • 1
  • 15
  • 29
1

They have the same effect for this case.

The 1st one is copy initialization,

Otherwise (if neither T nor the type of other are class types), standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T.

the 2nd one is direct-list-initialization.

Otherwise (if T is not a class type), if the braced-init-list has only one element and either T isn't a reference type or is a reference type whose referenced type is same as or is a base class of the type of the element, T is direct-initialized (in direct-list-initialization) or copy-initialized (in copy-list-initialization), except that narrowing conversions are not allowed.

and

Otherwise, standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T, and the initial value of the object being initialized is the (possibly converted) value.

As build-in types, one of the potential differences is that narrowing conversions are not allowed in list initialization. (Even it won't be applied in this case because the initializers have been specified as float literals.)

songyuanyao
  • 169,198
  • 16
  • 310
  • 405