C++: using curly braces to prevent narrowing during assignment
Asked Answered
C

1

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?

Connective answered 19/4, 2016 at 11:18 Comment(3)
if you want narrowing?Orpine
I'd say: do not use them in assignmentsIntake
Have a read of: herbsutter.com/2013/05/09/gotw-1-solution and possibly herbsutter.com/2013/08/12/…Textualism
A
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.

Adaptation answered 19/4, 2016 at 14:16 Comment(1)
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, en.cppreference.com/w/cpp/language/operator_assignment the T = {val} is interpreted as T = T{val}Noli

© 2022 - 2024 — McMap. All rights reserved.