C++: Variables and Basic Data Types
Last updated: 2026-08-26
In Lesson 02 we set up the development environment and can compile and run programs.
But programs can't just output fixed text — they need to be able to remember things and process data. That's what variables are for.
Just like in math, you need to define x, y, z first; in programming, you must "declare" variables before you can store data.
1. What is a Variable?
(1) 1.1 Variables in Everyday Life
| Real-life scenario | Programming equivalent |
|---|---|
| You have a name, but your age changes every year | Variable: its value can change |
| You have an ID number that never changes | Constant: its value cannot change |
| You have a cup that can hold water or cola | Variable: type is fixed (cup), value can change (what's inside) |
A variable is a "box" in memory — you can put things in it (assign values) and take things out (read values).
(2) 1.2 Why Do We Need Variables?
Without variables, programs can only do "rigid" things:
// Without variables, you can only output fixed text
std::cout << "Hello, World!" << std::endl;
With variables, programs come "alive":
// With variables, you can remember user input
std::string name;
std::cin >> name;
std::cout << "Hello, " << name << "!" << std::endl;
2. Basic Data Types
C++ is a statically typed language — every variable must have its type declared first, and the type cannot change.
(1) 2.1 Five Basic Data Types
| Type | Keyword | Size | Range | Real-life Analogy |
|---|---|---|---|---|
| Integer | int |
4 bytes | -2,147,483,648 ~ 2,147,483,647 | Number of people, age, year |
| Floating-point | double |
8 bytes | Approx. ±1.7 × 10³⁰⁸ | Height, weight, price |
| Character | char |
1 byte | -128 ~ 127 (or 0 ~ 255) | Single letter, grade (A/B/C) |
| Boolean | bool |
1 byte | true or false |
Whether passed, whether adult |
| String | string |
Variable | Any length | Name, address, a sentence |
💡 Tip: string is not a "basic type" in C++, but a type provided by the standard library. You need #include <string> before using it.
(2) 2.2 Declaring Variables
Syntax:
Type variableName;
Example:
int age; // Declare an integer variable named age
double price; // Declare a floating-point variable named price
char grade; // Declare a character variable named grade
bool isPassed; // Declare a boolean variable named isPassed
std::string name; // Declare a string variable named name
(3) 2.3 Declaring and Assigning at the Same Time (Initialization)
Syntax:
Type variableName = value;
Example:
int age = 25; // Declare age and assign 25
double price = 19.99; // Declare price and assign 19.99
char grade = 'A'; // Declare grade and assign 'A' (note: characters use single quotes)
bool isPassed = true; // Declare isPassed and assign true
std::string name = "MOTO"; // Declare name and assign "MOTO" (note: strings use double quotes)
💡 Tip: C++11 introduced a more modern initialization style (uniform initialization):
int age = {25}; // Uniform initialization (recommended)
double price{19.99}; // Can omit the equals sign (recommended)
This style prevents narrowing conversions (e.g., assigning 3.14 to int will cause an error instead of silently truncating).
3. Using Variables
▶ Example 1: Calculate the Area of a Circle (Difficulty ⭐)
#include <iostream>
int main() {
const double PI = 3.14159; // Constant (covered later)
double radius;
std::cout << "Please enter the radius of the circle:";
std::cin >> radius;
double area = PI * radius * radius;
std::cout << "The area of the circle is:" << area << std::endl;
return 0;
}
Output:
Please enter the radius of the circle:
The area of the circle is:
Run result:
Please enter the radius of the circle:5
The area of the circle is:78.5397
Code breakdown:
const double PI = 3.14159;— Declare a constant PI whose value cannot changedouble radius;— Declare a floating-point variable radiusstd::cin >> radius;— Read user input from the keyboard and store it in radiusdouble area = PI * radius * radius;— Calculate the area and store the result in areastd::cout << ...— Output the result
4. Variable Naming Rules
C++ has strict rules for variable names:
(1) 4.1 Hard Rules (Must Follow)
| Rule | Valid Example | Invalid Example |
|---|---|---|
| Can only contain letters, digits, and underscores | my_age, score2 |
my-age (no hyphens allowed) |
| Cannot start with a digit | age2 |
2age |
| Case-sensitive | age and Age are different variables |
— |
| Cannot be a keyword | int myInt = 5; |
int int = 5; (int is a keyword) |
C++ Keyword List (partial):
int, double, char, bool, string, if, else, for, while,
return, class, public, private, new, delete, ...
(2) 4.2 Soft Rules (Strongly Recommended)
The compiler doesn't enforce these, but following them makes your code more readable:
| Rule | Recommended Style | Not Recommended |
|---|---|---|
| Variable names should be meaningful | studentAge |
a, x1 |
| Use camelCase for multi-word names | studentAge, totalScore |
student_age, total_score |
| Constants should be ALL_CAPS | const int MAX_SIZE = 100; |
const int maxSize = 100; |
💡 Tip: Different teams may have different naming conventions. This tutorial uses camelCase.
5. Constants (const)
Some values should never change, such as π, the number of days in a year, or the maximum length of an array.
(1) 5.1 Why Do We Need Constants?
Without constants (bad example):
double circumference = 3.14159 * diameter; // This 3.14159 is a "magic number"
double area = 3.14159 * radius * radius; // If π is wrong, you have to fix it in two places
With constants (good example):
const double PI = 3.14159;
double circumference = PI * diameter; // Clear and easy to change
double area = PI * radius * radius;
(2) 5.2 How to Declare Constants
Syntax:
const Type CONST_NAME = value;
Example:
const int DAYS_PER_WEEK = 7;
const double PI = 3.14159;
const std::string SCHOOL_NAME = "Meijia Vocational College";
💡 Tip: Constant names are typically ALL_CAPS with underscores separating words — this is a C++ convention.
(3) 5.3 Characteristics of Constants
- Must be initialized (must be assigned a value when declared)
const int MAX_SIZE; // ❌ Error: constant must be initialized
- Cannot be modified
const int MAX_SIZE = 100;
MAX_SIZE = 200; // ❌ Error: cannot modify a constant's value
6. Input and Output (cin and cout Advanced)
(1) 6.1 Reading Multiple Variables at Once
cin can read multiple variables in one statement, separated by spaces or newlines:
#include <iostream>
#include <string>
int main() {
int age;
std::string name;
std::cout << "Please enter your name and age(separated by spaces):";
std::cin >> name >> age; // Read two variables at once
std::cout << "Hello," << name << "! You are " << age << " years old。" << std::endl;
return 0;
}
Run result:
Please enter your name and age(separated by spaces):MOTO 35
Hello,MOTO! You are 35 years old。
(2) 6.2 Mixing cin and cout
#include <iostream>
#include <string>
int main() {
std::string name;
int age;
double height;
std::cout << "Please enter your name: ";
std::cin >> name;
std::cout << "Please enter your age: ";
std::cin >> age;
std::cout << "Please enter your height (meters): ";
std::cin >> height;
std::cout << "========== Personal Info ==========" << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << " years old" << std::endl;
std::cout << "Height: " << height << " meters" << std::endl;
return 0;
}
7. Common Errors and Debugging
(1) 7.1 Forgetting to Initialize a Variable
Error example:
#include <iostream>
int main() {
int x; // Declared x but didn't assign a value
std::cout << x << std::endl; // ❌ x's value is "garbage" — undefined
return 0;
}
Correct approach:
int x = 0; // Initialize when declaring
std::cout << x << std::endl; // ✅ Outputs 0
💡 Tip: Modern C++ compilers will warn you about using uninitialized variables, but don't rely on the compiler — develop the good habit of always initializing.
(2) 7.2 Type Mismatch
Error example:
int age;
std::cin >> age;
// If the user enters "abc", age will remain unchanged (or worse)
Correct approach (we'll learn how to validate input later):
int age;
std::cin >> age;
if (std::cin.fail()) {
std::cout << "InputError!Please enter a number." << std::endl;
}
(This topic will be covered in detail in Lesson 08 — for now, just be aware of the issue.)
8. Practice: Simple Calculator
▶ Example 2: Addition, Subtraction, Multiplication, Division Calculator (Difficulty ⭐⭐)
#include <iostream>
int main() {
double num1, num2;
char op;
std::cout << "Please enter the first number: ";
std::cin >> num1;
std::cout << "Please enter an operator (+ - * /): ";
std::cin >> op;
std::cout << "Please enter the second number: ";
std::cin >> num2;
double result;
if (op == '+') {
result = num1 + num2;
} else if (op == '-') {
result = num1 - num2;
} else if (op == '*') {
result = num1 * num2;
} else if (op == '/') {
if (num2 != 0) {
result = num1 / num2;
} else {
std::cout << "Error: Divisor cannot be 0!" << std::endl;
return 1; // Abnormal exit
}
} else {
std::cout << "Error: Unsupported operator!" << std::endl;
return 1;
}
std::cout << "Result: " << num1 << " " << op << " " << num2 << " = " << result << std::endl;
return 0;
}
Output:
Please enter the first number:
Please enter an operator (+ - * /):
Please enter the second number:
Error: Divisor cannot be 0!
Error: Unsupported operator!
Result: =
Run result:
Please enter the first number: 10
Please enter an operator (+ - * /): *
Please enter the second number: 5
Result: 10 * 5 = 50
💡 Tip: This program uses if-else (covered in detail in Lesson 06) — you can copy it for now and understand the general approach.
❓ FAQ
int stores whole numbers (e.g., 25, -3), double stores floating-point numbers (e.g., 19.99, 3.14). Rule of thumb: counting/age/years → int; price/height/average scores → double.char is a single character, using single quotes (e.g., 'A'); string is multiple characters, using double quotes (e.g., "Hello"). Note that "A" and 'A' are completely different types.const is a C++ keyword with type checking — safer and recommended (e.g., const double PI = 3.14159;). #define is a C-style macro without type checking — not recommended.int Age = 25;.▶ Example 3: Type Conversion (Difficulty ⭐)
#include <iostream>
int main() {
int a = 5;
double b = 3.7;
// Implicit conversion
double c = a + b;
std::cout << "Implicit conversion: " << c << std::endl;
// Explicit conversion (C-style)
int d = (int)b;
std::cout << "C-style cast: " << d << std::endl;
// C++-style conversion
int e = static_cast<int>(b);
std::cout << "C++-style cast: " << e << std::endl;
return 0;
}
Output:
Implicit conversion:
C-style cast:
C++-style cast:
static_cast<T>() is the recommended type conversion method in C++, safer than the C-style (T).
- Variables are "boxes" in memory used to store data
- C++ has 5 basic data types:
int,double,char,bool,string - Declaring a variable:
Type variableName; - Initializing a variable:
Type variableName = value;(uniform initializationType variableName{value};is recommended) - Constants are declared with
const, their values cannot change, and they must be initialized - Use
cinfor input,coutfor output - Variable names should be meaningful and follow naming rules
📖 Summary
- Basic types: int, double, char, bool
- Type conversion: static_cast, dynamic_cast
- auto: automatic type deduction
- const: constant, cannot be modified
📝 Exercises
- Basic (Difficulty ⭐):
Write a program that declares three variables:
name(string),age(integer),score(floating-point), assigns values to each, and outputs them.
My name is Alice,this year 20 years old,FinalScore 92.5 points。
-
Intermediate (Difficulty ⭐⭐): Write a program that lets the user input the radius of a circle, then calculates and outputs the circumference and area (circumference = 2πr, area = πr²).
-
Define π as a constant (3.14159)
-
Output with 2 decimal places (hint: use
std::fixedandstd::setprecision, requires#include <iomanip>) -
Challenge (Difficulty ⭐⭐⭐): Write a program that converts Fahrenheit to Celsius:
-
Let the user input a Fahrenheit temperature
-
Use the formula C = (F - 32) × 5/9 to calculate Celsius
-
Output the result (1 decimal place)
-
Example: input 68, output "68°F = 20.0°C"
- Variables are data storage units in memory; they must be declared before use
- C++ basic types: int (integer), double (floating-point), char (character), bool (boolean), string (string)
- Variable initialization methods: = assignment / uniform initialization {}
- Constants are declared with const; their values cannot be modified and must be initialized
- Naming rules: letters/digits/underscores, cannot start with a digit, case-sensitive
13. 🚀 Next Step
Now that you've learned about variables and data types, next we'll learn C++ operators (Lesson 04) — enabling variables to perform arithmetic, comparisons, and logical judgments.