When a new variable is initialized, the compiler can figure out what the type of the variable is automatically by the initializer. For this, it suffices to use
Here,
Variables that are not initialized can also make use of type deduction with the
A second method, known as constructor initialization (introduced by the C++ language), encloses the initial value between parentheses (
For example:
Finally, a third method, known as uniform initialization, similar to the above, but using curly braces (
For example:
auto
as the type specifier for the variable:
| |
Here,
bar
is declared as having an
auto
type; therefore, the type of
bar
is the type of the value used to initialize it: in this case it uses the type of
foo
, which is
int
.
Variables that are not initialized can also make use of type deduction with the
decltype
specifier:
| |
Here, bar
is declared as having the same type as foo
.
In C++, there are three ways to initialize variables. They are all equivalent and are reminiscent of the evolution of the language over the years:
The first one, known as c-like initialization (because it is inherited from the C language), consists of appending an equal sign followed by the value to which the variable is initialized:
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:
| |
A second method, known as constructor initialization (introduced by the C++ language), encloses the initial value between parentheses (
()
):
type identifier (initial_value);
For example:
| |
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):
type identifier {initial_value};
For example:
| |