Difference of {} and = in a declaration

Asked

Viewed 62 times

3

What is the difference of two statements? On what occasions should I use each one?

- int Num{15};
- int Num = 15;

1 answer

6


This is called Uniform Initialization Syntax or Uniform Boot Syntax which is the preferred way to initialize variables in C++ since version 11.

It is true that the initialization of primitive simple types so does not change much and everyone is accustomed to use the assignment operator, which makes more sense, so it is strange even the shape of the UIS. But for more complex types it is more interesting because it works as a construction syntax where to pass information and the type will know how to initialize the object with this information (I won’t go into this subject here). Before it was even possible to do this with the use of parentheses, but ends up confusing with the call of a function.

Some people prefer to use the keys at all to get everything really uniform.

So you’re just saying you’re going to create a variable again Num who’s kind int and will call the builder of this type passing the 15 as an argument for him to turn to create the object. And the compiler knows what to do in this case. If it were another type the compiler would call a constructor even.

Example:

std::vector<int> vetor{10};

Here is creating the variable vetor of the kind vector and is passing 10 as argument. Looking at the documentation we know that it has a constructor that gets the size that it should create the vector.

This is different:

std::vector<int> vetor = {10};

Here is creating the variable and is assigning a data list to the vector, in case there will be an element with the value 10.

I know, it sounds confusing, but it’s a matter of getting used to it. C++ started with some initial errors and gradually improved the syntax. At the same time there are many different things that need to be expressed.

But do this:

int Num{15.1};

Gives error. If you do with the assignment it discards the decimal part and initializes with the whole part, almost always not what you want. New syntaxes can treat things a little better than old problems.

In some cases it may be interesting to use this syntax so as not to have to say which type is creating, for example in the return in a function, the syntax with the keys infers the type by the function signature.

Can see more on Wikipedia. Understand more about the problem (plus).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.