0% found this document useful (0 votes)
7 views

Initialization of Variables

There are three ways to initialize variables in C++: 1) C-like initialization, which uses an equal sign followed by the initial value 2) Constructor initialization, which encloses the initial value in parentheses 3) Uniform initialization, which uses curly braces instead of parentheses and was introduced in C++11 All three methods of initializing variables are valid and equivalent in C++.

Uploaded by

icul1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Initialization of Variables

There are three ways to initialize variables in C++: 1) C-like initialization, which uses an equal sign followed by the initial value 2) Constructor initialization, which encloses the initial value in parentheses 3) Uniform initialization, which uses curly braces instead of parentheses and was introduced in C++11 All three methods of initializing variables are valid and equivalent in C++.

Uploaded by

icul1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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;
}

You might also like