Initialization occurs when you provide a variable with a value. In C++, there are several methods used to declare and initialize a variable.
The most basic way to initialize a variable is to provide it with a value at the time of its declaration. For example:
#include <iostream>using namespace std;int main() {int a = 20;cout << "The value of variable a is "<< a << endl;}
However, we can also use curly braces to initialize variables in C++:
#include <iostream>#include <vector>using namespace std;int main() {int a{20};cout << "The value of variable a is: "<< a << endl;string b{"This is a string"};cout << "The value of variable b is: "<< b << endl;std::vector<int> c{10, 5};cout<< "The values of variable c are: " << endl;for(int i=0; i<c.size(); i++){cout << c[i] << endl;}}
The code above shows how curly braces can be used to declare various types of variables and assign values to them. Using curly braces instead of an =
sign is one of the many ways to initialize.
Using curly braces to initialize a variable also prevents narrowing. Narrowing, or more precisely narrowing conversion, is the implicit conversion of arithmetic values that includes a loss of accuracy.
#include <iostream>int main(){int myint(3.14);std::cout << "myint: " << myint << std::endl;int myint1{3.14};std::cout << "myint: " << myint1 << std::endl;}
In the code above, the compiler compiles line 4 even though it is converting a decimal number to an integer. This results in a loss of accuracy. However, when the same initialization is done using braces in line 7, the compiler generates an error that alerts the user to the occurrence of narrowing.