Initialization of Variables
Initialization of Variables
When the variables in the example above are declared, they have an undetermined value until
they are assigned a value for the first time. But it is possible for a variable to have a specific
value from the moment it is declared. This is called the initialization of the variable.
In C++, there are three ways to initialie variables. They are all e!uivalent and are reminiscent of
the evolution of the language over the years"
The first one, #nown as c-like initialization $because it is inherited from the C language%, consists
of appending an e!ual sign followed by the value to which the variable is initialied"
type identifier = initial_value;
&or example, to declare a variable of type int called x and initialie it to a value of ero from the
same moment it is declared, we can write"
int x = 0;
' second method, #nown as constructor initialization $introduced by the C++ language%,
encloses the initial value between parentheses $()%"
type identifier (initial_value);
&or example"
int x (0);
&inally, a third method, #nown 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
()**%"
type identifier {initial_value};
&or example"
int x {0};
'll three ways of initialiing variables are valid and e!uivalent in C++.
1
2
3
4
5
6
// initializatin f varia!le"
#in$lude %i"trea&'
u"in( na&e"pa$e "td;
int &ain ()
6
)
*
+
10
11
12
13
14
15
16
1)
1*
{
int a=5; // initial value, 5
int !(3); // initial value, 3
int ${2}; // initial value, 2
int re"ult; // initial value
undeter&ined
a = a - !;
re"ult = a . $;
$ut %% re"ult;
return 0;
}