Variables store information so your program can use it later. Declaration tells the computer about the variable, and initialization gives it a starting value.
0
0
Variable declaration and initialization in C++
Introduction
When you want to remember a number, like a score in a game.
When you need to store a name or word to use later.
When you want to keep track of a setting or choice.
When you want to prepare a place to store data before using it.
When you want to update or change information during the program.
Syntax
C++
type variableName = value; // Example: int age = 25;
type is the kind of data (like int for numbers, char for letters).
You can declare a variable without giving it a value first, but it's safer to initialize it right away.
Examples
This creates a variable named
number that holds an integer value 10.C++
int number = 10;
This creates a variable
price that holds a decimal number.C++
double price = 9.99;
This creates a variable
letter that holds a single character.C++
char letter = 'A';
This creates a variable
isOpen that holds a true/false value.C++
bool isOpen = true;Sample Program
This program shows how to declare and initialize different types of variables, then print their values.
C++
#include <iostream> int main() { int age = 30; // Declare and initialize an integer variable double height = 1.75; // Declare and initialize a double variable char grade = 'B'; // Declare and initialize a char variable bool isStudent = false; // Declare and initialize a bool variable std::cout << "Age: " << age << "\n"; std::cout << "Height: " << height << " meters\n"; std::cout << "Grade: " << grade << "\n"; std::cout << "Is student: " << isStudent << "\n"; return 0; }
OutputSuccess
Important Notes
In C++, bool variables print as 1 (true) or 0 (false) when using std::cout.
Always choose the right type for your data to avoid errors.
Initializing variables helps prevent unexpected values.
Summary
Variables hold data your program uses.
Declaration tells the program about the variable's type and name.
Initialization gives the variable its first value.