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?
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true. See event loop.
The curly brackets means an initializer list in this case of arrays. Let assume for example that you want to define an array with elements 1, 2, 3, 4, 5. int a[5] = { 1, 2 }; In this case a[0] will be equal tp 1 a[1] will be equal to 2 and all other elements will be equal to 0.
Definition of curly bracket : either one of the marks { or } that are used as a pair around words or items that are to be considered together.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With