Aditya Prakash
Aditya Prakash

Reputation: 1589

Difference between = and {} syntaxes for initializing a variable in C++

I have read quite a few C++ codes, and I have come across two methods of initialising a variable.

Method 1:

int score = 0;

Method 2:

int score {};

I know that int score {}; will initialise the score to 0, and so will int score = 0;

What is the difference between these two? I have read initialization: parenthesis vs. equals sign but that does not answer my question. I wish to know what is the difference between equal sign and curly brackets, not parenthesis. Which one should be used in which case?

Upvotes: 2

Views: 4638

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

int score = 0; performs copy initialization, as the effect, score is initialized to the specified value 0.

Otherwise (if neither T nor the type of other are class types), standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T.

int score {}; performs value initialization with braced initializer, which was supported since C++11, as the effect,

otherwise, the object is zero-initialized.

score is of built-in type int, it's zero-initialized at last, i.e. initialized to 0.

If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T.

Upvotes: 7

b4l8
b4l8

Reputation: 141

You may have some interest in ISO/IEC 14882 8.5.1. It will tell you that a brace-or-equal-initializer can be assignment-expression or braced-init-list. In Method2, you are using an default initializer on a scalar type, witch should be set to zero.

Upvotes: 0

Related Questions