Beginner7 min readLesson 6 of 50
What is a Variable?
A variable is a named storage location in memory that holds a value. You must declare the variable type before using it.
Syntax
type variableName = value;
Example
#include <iostream>
using namespace std;
int main() {
int age = 25;
double price = 9.99;
char grade = 'A';
bool isStudent = true;
string name = "Alex";
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Price: " << price << endl;
cout << "Grade: " << grade << endl;
cout << "Student: " << isStudent << endl;
return 0;
}
Output:
Name: Alex
Age: 25
Price: 9.99
Grade: A
Student: 1
Common Variable Types
| Type | Description | Example |
int | Integer numbers | int x = 10; |
double | Decimal numbers (high precision) | double pi = 3.14; |
float | Decimal numbers (less precision) | float f = 3.14f; |
char | Single character | char c = 'A'; |
bool | True or false | bool b = true; |
string | Text (sequence of characters) | string s = "Hi"; |
Naming Rules
- Names can contain letters, digits, and underscores.
- Must start with a letter or underscore (not a digit).
- Case-sensitive:
age and Age are different variables.
- Cannot use C++ reserved keywords (e.g.,
int, return).
int myAge = 30; // valid
int _count = 0; // valid
int 1name = 5; // INVALID — starts with digit
int int = 10; // INVALID — reserved keyword
Declare Multiple Variables
int x = 1, y = 2, z = 3;
cout << x + y + z; // Output: 6
Note: In C++, string requires the #include <string> header, but it is usually included automatically via #include <iostream>.
Exercise
Declare variables to store: a product name (string), price (double), quantity (int), and whether it is in stock (bool). Print all four values.
Show Solution
#include <iostream>
using namespace std;
int main() {
string productName = "Laptop";
double price = 999.99;
int quantity = 10;
bool inStock = true;
cout << "Product: " << productName << endl;
cout << "Price: $" << price << endl;
cout << "Quantity: " << quantity << endl;
cout << "In Stock: " << inStock << endl;
return 0;
}
Quiz
Which variable name is valid in C++?
- A)
2score - B)
my-score - C)
my_score - D)
return
Answer
C) my_score — underscores are allowed; hyphens are not; names cannot start with digits; reserved words cannot be used.
What type stores a single character in C++?
- A)
string - B)
int - C)
char - D)
letter
Answer
C) char
Summary
- Variables are declared as
type name = value;
- Common types:
int, double, char, bool, string.
- Names are case-sensitive and cannot start with a digit.
- Multiple variables of the same type can be declared on one line.