1

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?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Aditya Prakash
  • 1,549
  • 2
  • 15
  • 31

2 Answers2

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Is there an advantage in using one over the other? – Aditya Prakash Dec 19 '19 at 07:46
  • 1
    An entire story should be written about brace initializers. – Victor Dec 19 '19 at 07:47
  • The advantage is that you avoid copy-construction – Victor Dec 19 '19 at 07:47
  • 1
    @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*. – songyuanyao Dec 19 '19 at 07:50
  • 2
    That depends on what you are initializing. In the example as written there is no difference. – super Dec 19 '19 at 07:51
  • 1
    Empty braces is *value-initialization*, which for the case of a variable of type `int`, resolves to zero-initialization – M.M Dec 19 '19 at 08:02
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.

b4l8
  • 141
  • 5