2

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Is there an advantage in using one over the other?
An entire story should be written about brace initializers.
@AdityaPrakash Since they have the same effect, I think it's just a coding style issue. For the 1st one, it could be used to initialize to the specified value; for the 2nd one, it could be used to initialize to the default value.
That depends on what you are initializing. In the example as written there is no difference.
Empty braces is value-initialization, which for the case of a variable of type int, resolves to zero-initialization
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.