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:

CPP
// Without variables, you can only output fixed text
std::cout << "Hello, World!" << std::endl;

With variables, programs come "alive":

CPP
// 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:

TEXT 📖 Display only
Type variableName;

Example:

CPP
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:

TEXT 📖 Display only
Type variableName = value;

Example:

CPP
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):

CPP
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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Please enter the radius of the circle:
The area of the circle is:

Run result:

TEXT 📖 Display only
Please enter the radius of the circle:5
The area of the circle is:78.5397

Code breakdown:

  1. const double PI = 3.14159; — Declare a constant PI whose value cannot change
  2. double radius; — Declare a floating-point variable radius
  3. std::cin >> radius; — Read user input from the keyboard and store it in radius
  4. double area = PI * radius * radius; — Calculate the area and store the result in area
  5. std::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):

TEXT 📖 Display only
int, double, char, bool, string, if, else, for, while, 
return, class, public, private, new, delete, ...

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):

CPP
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):

TEXT 📖 Display only
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:

CPP
const Type CONST_NAME = value;

Example:

CPP
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

  1. Must be initialized (must be assigned a value when declared)
CPP
const int MAX_SIZE; // ❌ Error: constant must be initialized
  1. Cannot be modified
CPP
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:

CPP
#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:

TEXT 📖 Display only
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

CPP
#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:

CPP
#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:

CPP
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:

CPP
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):

CPP
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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:

TEXT 📖 Display only
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

Q What's the difference between int and double? When should I use which?
A 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.
Q Why does char use single quotes and string use double quotes?
A 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.
Q What's the difference between const and #define?
A 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.
Q Can variable names use Chinese characters?
A Theoretically yes (C++11 supports Unicode identifiers), but it's strongly discouraged — cross-compiler support varies and code becomes hard to maintain. Don't write code like int Age = 25;.

▶ Example 3: Type Conversion (Difficulty ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Implicit conversion: 
C-style cast: 
C++-style cast: 
💡 Tip: static_cast<T>() is the recommended type conversion method in C++, safer than the C-style (T).



📖 Summary

📝 Exercises

  1. Basic (Difficulty ⭐): Write a program that declares three variables: name (string), age (integer), score (floating-point), assigns values to each, and outputs them.
TEXT 📖 Display only
My name is Alice,this year 20 years old,FinalScore 92.5 points。
  1. 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²).

  2. Define π as a constant (3.14159)

  3. Output with 2 decimal places (hint: use std::fixed and std::setprecision, requires #include <iomanip>)

  4. Challenge (Difficulty ⭐⭐⭐): Write a program that converts Fahrenheit to Celsius:

  5. Let the user input a Fahrenheit temperature

  6. Use the formula C = (F - 32) × 5/9 to calculate Celsius

  7. Output the result (1 decimal place)

  8. Example: input 68, output "68°F = 20.0°C"

  1. C++ basic types: int (integer), double (floating-point), char (character), bool (boolean), string (string)

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.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏