When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There are two ways to do this in C++:
The first one, known as c-like initialization, is done by appending an equal sign followed by the value to which the variable will be initialized:
For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write:
The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (
For example:
Both ways of initializing variables are valid and equivalent in C++.
The first one, known as c-like initialization, is done by appending an equal sign followed by the value to which the variable will be initialized:
type identifier = initial_value ;
For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is declared, we could write:
|
The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (
()
): type identifier (initial_value) ;
For example:
|
Both ways of initializing variables are valid and equivalent in C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|