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.