English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Variables are names given by the user. Data types are also used to declare and initialize variables, which allocate memory to the variable. There are several data types, such as int, char, float, etc., which can allocate memory to the variable.
There are two methods to initialize variables. One is static initialization, in which a value is assigned to the variable in the program; the other is dynamic initialization, in which a value is assigned to the variable at runtime.
The following is the syntax of variable initialization.
datatype variable_name = value;
Here,
datatype-The data type of the variable, such as int, char, float, etc.
variable_name-This is the variable name given by the user.
Value-Initialize any value for the variable. By default, it is zero.
The following is an example of variable initialization.
#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 Result
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 as a and b.
int a = 20; int b;
Variable a is initialized with a value from the program, while variable b is dynamically initialized.
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;