Home   |   About   |   Terms   |   Contact    
Read & Learn
 

What is Initialization? Different Types of Initialization, Why Initialization is necessary in C++?

C++

☯ All C++ Articles     ☯ All Articles


A new product.




Popular Google Pages:




This article is regarding What is Initialization? Different Types of Initialization, Why Initialization is necessary in C++?
Last updated on: .



◕ What is Initialization in C++ ?

- Initialization means declaring the initial value of a Variable.
In other word we can say that Initialization combines an assignment with its declaration.



◕ Example of Initialization:

Let a simple program:
#include <iostream>
using namespace std;
int india = 29;
int main()
{
cout << "The total states in India is : " << india << endl;
return 0;
}

The above program will give us result as:
The total states in India is : 29



◕ Different ways of Initialization in C++?

- 1. We can directly declare a constant as the value of a variable.
Example:
int india = 29;
// It Initializes india as 29.

- 2. We can Initialize a variable to another variable, provide that the other variable has been defined first.
Example:
int india = 29;
int states = india;
// It Initializes states to 29.

- 3. We can Initialize a variable to an expression, provided that all the values in the expression are known.
Example:
int india = 29;
int states = india;
int capitals = states + 7;
// It Initializes capitals to 29 + 7 = 36

- 4;. We can also Initialize a variable by the following way,
int india(29);
// It Initializes india as 29.

- 5. Other Expressions to Initialize a variable
int india{29};
//It Initialize india as 29.

- 6.
int india = {29};

- 7.
int india{};
//It Initialize india as 0.
Note: Without ' = ' sign.

- 8.
int india = {};
//It Initialize india as 0.
Note: With ' = ' sign.





◕ Why Initialization is necessary?

- 1) Sometimes if we do not Initialize the value of a variable, then it takes whatever the value left in that memory location by the previous program, or prior to the creation of that variable.

- 2) If the variable starts with a known value or an initial value, then it makes us easier to work when things go wrong. Because we know the initial value and as a result it makes us easier to find and solve the problem.

- 3) If we know what the initial value of a variable should be, then we should Initialize it. Because it protects us from forgetting to assign the value later.




Popular Google Pages:





Top of the page

Amazon & Flipkart Special Products

   


Top of the page