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?
int score = 0;
performs copy initialization, as the effect, score
is initialized to the specified value 0
.
Otherwise (if neither
T
nor the type ofother
are class types), standard conversions are used, if necessary, to convert the value ofother
to the cv-unqualified version ofT
.
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 toT
.