Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 527
James Avatar asked Apr 19 '16 11:04

James


People also ask

What is the purpose of curly braces?

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.

What does curly braces do in C++?

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.

What are the curly braces specifically used for when working with arrays write an example?

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.

What does curly brackets mean in English?

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.


1 Answers

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.

like image 84
max66 Avatar answered Oct 27 '22 00:10

max66