Variable initialization in C++


Variables are the names given by the user. A datatype is also used to declare and initialize a variable which allocates memory to that variable. There are several datatypes like int, char, float etc. to allocate the memory to that variable.

There are two ways to initialize the variable. One is static initialization in which the variable is assigned a value in the program and another is dynamic initialization in which the variables is assigned a value at the run time.

The following is the syntax of variable initialization.

datatype variable_name = value;

Here,

datatype − The datatype of variable like int, char, float etc.

variable_name − This is the name of variable given by user.

value − Any value to initialize the variable. By default, it is zero.

The following is an example of variable initialization.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a = 20;
   int b;
   cout << "The value of variable a : "<< a; // static initialization
   cout << "\nEnter the value of variable b : "; // dynamic initialization
   cin >> b;
   cout << "\nThe value of variable b : "<< b;
   return 0;
}

Output

The value of variable a : 20
Enter the value of variable b : 28
The value of variable b : 28

In the above program, two variables are declared a and b.

int a = 20;
int b;

The variable a is initialized with a value in the program while the variable b is initialized dynamically.

cout << "The value of variable a : "<< a; // static initialization
cout << "\nEnter the value of variable b : "; // dynamic initialization
cin >> b;
cout << "\nThe value of variable b : "<< b;

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements