Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between assigning a value to a variable using the equal operator or using curly braces?

Tags:

c++

I saw a code where a programmer used curly braces to initialize a variable

int var{ 5 };

instead of using the assignment operator

int var = 5;

I know assigning a value to lhs variable using curly braces is a C++11 syntax. Is there any difference between using the two?

Thank you for replies.

like image 287
Andy Avatar asked Dec 28 '25 19:12

Andy


2 Answers

They are different kinds of initialization:

T a{b};   // list initialization
T a = b;  // copy initialization
T a(b);   // direct initialization

There is no difference for ints but there can definitely be differences for other types. For instance, copy initialization might fail if your constructor is explicit, whereas the other two would succeed. List initialization disallows narrowing conversions, but for the other two those are fine.

like image 54
Barry Avatar answered Dec 30 '25 23:12

Barry


As far as I know, there is no difference in the two for integers. The {} syntax was made to(however, not limited to, because it is also used for initializer_list) prevent programmers from triggering http://en.wikipedia.org/wiki/Most_vexing_parse, and so instead of std::vector<int> v() to initialize v you write std::vector<int> v{};.

The {} has different behaviours depending on the usage, it can be a call to constructor, a initializer list and even a list of values to initialize members of user-defined class in order of definition.

Example of the last:

class Q{
public:
    int a;
    int b;
    float f;
};

int main()
{
    Q q{2, 5, 3.25f};
}
like image 23
Creris Avatar answered Dec 30 '25 23:12

Creris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!