2

Recently I saw a quite old code in C++, where int var(12) was used instead of int var=12. Why does it work? And should I avoid writing this style of declaration?

0

1 Answer 1

0

There are three ways of initializing variables are valid in C++.

type identifier = initial_value;

For example, to declare a variable of type int called x and initialize it to a value of zero from the same moment it is declared, we can write:

int a=5; // initial value: 5 

type identifier (initial_value);

A second method, known as constructor initialization (introduced by the C++ language), encloses the initial value between parentheses (()):

int b(3); // initial value: 3 

type identifier {initial_value};

Finally, a third method, known as uniform initialization, similar to the above, but using curly braces ({}) instead of parentheses (this was introduced by the revision of the C++ standard, in 2011):

int c{2}; // initial value: 2 

You should check Documentation section Initialization of variables

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

2 Comments

They are not equivalent.() will perform certain narrowing conversions.
int a{1.0} is an error. int a(1.0) is legal. They are not the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.