- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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;