12

I'm familiar with using curly braces/ initializer lists to prevent narrowing when initializing a variable, but is it good practice to use it when assigning a value to a variable too?

For e.g.

int i{1};       // initialize i to 1
double d{2.0};  // initialize d to 2.0
i = {2};        // assign value 2 to i
i = {d};        // error: narrowing from double to int

Is there a reason not to use curly braces for assignment?

max66
  • 65,235
  • 10
  • 71
  • 111
James
  • 221
  • 1
  • 5

1 Answers1

4

Isn't a problem of initialization vs assignment.

It's a problem of different types.

If you try to initialize an int variable with a double, you get the same error.

And you can assign {d} to another double variable.

int main ()
 {
   int i{1};       // initialize i to 1
   //int i2{3.0};    // ERROR!
   double d{2.0};  // initialize d to 2.0  
   double d2{1.0}; // initialize d2 to 1.0
   i = {2};        // assign value 2 to i
   //i = {d};        // error: narrowing from double to int
   d2 = {d};       // OK

   return 0;
 }

Your example, enriched.

A good practice when assigning a value? Can be if you want to be sure not to lose precision.

An example: you can write a template assign() function in this way

template <typename X, typename Y>
void assign (X & x, Y const & y)
 { x = {y}; }

So you are sure to avoid narrowing

 // i is of type int
 assign(i, 23);    // OK
 assign(i, 11.2);  // ERROR! 

If (when) narrowing isn't a problem, you can avoid the curly braces.

max66
  • 65,235
  • 10
  • 71
  • 111
  • So basically the template is doing the same thing as the curly braces direct assignment syntax, but the template provides you a single place to turn on/off the narrowing warnings/errors. In principal both are same. And yes, the direct assignment is a good practice if you want to avoid narrowing. As per here, https://en.cppreference.com/w/cpp/language/operator_assignment the T = {val} is interpreted as T = T{val} – sanjivgupta Aug 20 '21 at 16:53