C++: Debugging Basics and Common Errors
Last updated: 2026-08-26
You can't write code perfectly on the first try — errors are the norm.
A true expert isn't someone who "never makes mistakes", but someone who can "quickly find and fix errors".
In this lesson, we'll learn how to debug C++ programs.
1. Three Types of Errors
C++ programs have three types of errors, each with different discovery timing and fixing difficulty.
| Error Type | When Discovered | Fixing Difficulty | Example |
|---|---|---|---|
| Compilation error | At compile time | ⭐ (easiest) | Missing semicolon, mismatched brackets |
| Runtime error | At runtime | ⭐⭐ (moderate) | Division by zero, array out of bounds |
| Logic error | After running (wrong result) | ⭐⭐⭐ (hardest) | Wrong algorithm, reversed condition |
2. Compilation Errors (Compiler Error)
(1) 2.1 Characteristics
- When discovered: At compile time (when entering
g++ xxx.cpp) - Symptom: The compiler reports an error directly and doesn't generate an executable
- Fix: Follow the error message to find the corresponding line and fix the syntax issue
(2) 2.2 Common Compilation Errors
Error 1: Missing Semicolon
▶ Example 2: Basic programming practice (Difficulty ⭐)
#include <iostream>
int main() {
int x = 5 // ❌ Missing semicolon
std::cout << x << std::endl;
return 0;
}
Output:
(Program output)
Compiler error message:
error: expected ';' before 'std'
💡 Tip: The compiler says "missing ; before std", but the actual missing semicolon is on the previous line (line 4).
Error 2: Mismatched Brackets
#include <iostream>
int main() {
if (5 > 3 { // ❌ Missing closing parenthesis
std::cout << "5 > 3" << std::endl;
}
return 0;
}
Compiler error message:
error: expected ')' before '{' token
💡 Tip: Use VS Code's bracket matching feature (place the cursor on a bracket and the matching one will be highlighted).
Error 3: Undeclared Variable
#include <iostream>
int main() {
x = 5; // ❌ x is not declared
std::cout << x << std::endl;
return 0;
}
Compiler error message:
error: 'x' was not declared in this scope
Error 4: Type Mismatch
#include <iostream>
int main() {
int x = 3.14; // ⚠️ Warning: assigning double to int, fractional part is lost
std::cout << x << std::endl;
return 0;
}
Compiler warning message:
warning: narrowing conversion of '3.1400000000000001e+0' from 'double' to 'int'
💡 Advice: Treat warnings as errors! Compile with g++ -Wall -Wextra -Werror to turn warnings into errors.
3. Runtime Errors (Runtime Error)
(1) 3.1 Characteristics
- When discovered: Compiles successfully, but crashes at runtime
- Symptom: The program suddenly exits or outputs garbage data
- Fix: Requires debugging to find the line of code causing the crash
(2) 3.2 Common Runtime Errors
Error 1: Division by Zero
#include <iostream>
int main() {
int x = 5;
int y = 0;
std::cout << x / y << std::endl; // ❌ Division by zero, runtime crash
return 0;
}
Run result:
Floating point exception (core dumped) // Linux
Or
Process ended, exit code -1073741676 // Windows
💡 Fix: Check if the divisor is zero before performing division.
Error 2: Array Out of Bounds
#include <iostream>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
std::cout << arr[10] << std::endl; // ❌ Accessing a non-existent element
return 0;
}
Run result:
0 // Outputs garbage value, or the program crashes
💡 Tip: C++ does not automatically check array bounds! This is one reason C++ is fast, but it's also a common source of bugs.
Error 3: Uninitialized Variable
#include <iostream>
int main() {
int x; // ❌ Not initialized
std::cout << x << std::endl; // Outputs garbage value
return 0;
}
Run result:
32767 // Outputs garbage value (may differ each run)
💡 Fix: Initialize variables when you declare them.
4. Logic Errors (Logic Error)
(1) 4.1 Characteristics
- When discovered: The program runs, but produces wrong results
- Symptom: No obvious error message — you need to compare expected vs actual results yourself
- Fix: The hardest! Requires carefully checking code logic
(2) 4.2 Common Logic Errors
Error 1: Reversed Condition
#include <iostream>
int main() {
int age;
std::cout << "Please enter your age: ";
std::cin >> age;
if (age < 18) { // ❌ Reversed! Should be age >= 18
std::cout << "You are an adult" << std::endl;
} else {
std::cout << "You are not yet an adult" << std::endl;
}
return 0;
}
💡 Debugging tip: Use cout to output key variable values and see where the program goes.
Error 2: Wrong Loop Condition
#include <iostream>
int main() {
// ❌ Want to output 1-10, but condition is i < 10, only outputs 1-9
for (int i = 1; i < 10; i++) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Error 3: = vs == Reversed
#include <iostream>
int main() {
int x = 5;
if (x = 10) { // ❌ This is assignment, not comparison! x becomes 10, condition always true
std::cout << "x is 10" << std::endl;
}
return 0;
}
💡 Anti-pitfall tip: Put the constant on the left: if (10 = x) will cause a compilation error.
5. Debugging Methods
(1) 5.1 Debugging with cout (Simplest)
Add cout at key positions to output variable values and see if the program executes as expected.
#include <iostream>
int main() {
int x = 5;
int y = 10;
std::cout << "[DEBUG] x = " << x << std::endl; // Debug output
std::cout << "[DEBUG] y = " << y << std::endl;
int sum = x + y;
std::cout << "[DEBUG] sum = " << sum << std::endl;
std::cout << "Result: " << sum << std::endl;
return 0;
}
💡 Tip: After debugging, remember to remove (or comment out) the debug output.
(2) 5.2 Using the IDE Debugger (Most Powerful)
VS Code + the C/C++ extension includes a debugger that can:
- Set breakpoints (pause the program at a specific line)
- Step through (run line by line)
- Watch variables (see variable values in real time)
Steps:
- In VS Code, click the area to the left of the line number to set a breakpoint (a red dot will appear)
- Press
F5(or click "Run and Debug"), then select "C++ (GDB/LLDB)" - The program will run and pause at the breakpoint
- Press
F10to step over, orF11to step into - In the "Variables" panel on the left, you can see all variable values
💡 Tip: The debugger is the ultimate tool, but it may seem complex for beginners. We recommend learning cout debugging first, then the debugger.
6. Common Error Summary
(1) 6.1 Compilation Error Quick Reference
| Error Message | Cause | Fix |
|---|---|---|
expected ';' before ... |
Missing semicolon | Add a semicolon at the end of the previous line |
expected ')' before ... |
Missing closing parenthesis | Add the missing parenthesis |
was not declared in this scope |
Undeclared variable | Declare the variable first |
undefined reference to ... |
Undefined function | Check for typos in the function name |
(2) 6.2 Runtime Error Quick Reference
| Symptom | Cause | Fix |
|---|---|---|
| Program suddenly exits | Division by zero | Check divisor before dividing |
| Garbage output | Array out of bounds | Check array index range |
| Strange large numbers | Uninitialized variable | Initialize at declaration |
(3) 6.3 Logic Error Quick Reference
| Symptom | Cause | Fix |
|---|---|---|
| Wrong result | Reversed condition | Carefully check if conditions |
| Wrong loop count | Wrong loop condition | Simulate the loop execution on paper |
| Never executes | Wrote = instead of == |
Put constants on the left |
7. Practice: Debugging a Buggy Program
▶ Example 1: Find the errors in the program (Difficulty ⭐⭐)
Buggy program:
#include <iostream>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
// Want to calculate the sum of all array elements
int sum = 0;
for (int i = 0; i <= 5; i++) { // ❌ Bug 1: i <= 5 causes out-of-bounds access
sum += arr[i];
}
std::cout << "Sum of array elements: " << sum << std::endl;
int x = 5;
if (x = 10) { // ❌ Bug 2: = should be ==
std::cout << "x is 10" << std::endl;
}
return 0;
}
Output:
Sum of array elements: 15
x not 10
Debugging process:
- First run: Program crashes (array out of bounds)
- Carefully check the
forloop, discover thati <= 5should bei < 5
- Second run: Program outputs "x is 10" (even though x is 5)
- Discover that
if (x = 10)is an assignment, change toif (x == 10)
Fixed program:
#include <iostream>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) { // ✅ Fix: i < 5
sum += arr[i];
}
std::cout << "Sum of array elements: " << sum << std::endl;
int x = 5;
if (x == 10) { // ✅ Fix: ==
std::cout << "x is 10" << std::endl;
} else {
std::cout << "x not 10" << std::endl;
}
return 0;
}
▶ Example 3: Debug print technique (Difficulty ⭐)
#include <iostream>
int main() {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
// Debug print: show values at each iteration
std::cout << "[DEBUG] i=" << i << ", sum=" << sum << std::endl;
}
std::cout << "Final Result: " << sum << std::endl;
return 0;
}
Output:
[DEBUG] i=1, sum=1
[DEBUG] i=2, sum=3
[DEBUG] i=3, sum=6
[DEBUG] i=4, sum=10
[DEBUG] i=5, sum=15
Final Result: 15
Expected output:
[DEBUG] i=1, sum=1
[DEBUG] i=2, sum=3
[DEBUG] i=3, sum=6
[DEBUG] i=4, sum=10
[DEBUG] i=5, sum=15
Final Result: 15
❓ FAQ
.exe causes it to flash and close — this is normal. Run it in a terminal instead; ② The program is in an infinite loop — press Ctrl+C to force-terminate it, then check the loop condition.launch.json. Key things to check: whether gdb is installed, and whether the program path in launch.json is correct.std::endl or std::flush to force-flush the buffer.📖 Summary
- C++ programs have three types of errors: compilation errors, runtime errors, and logic errors
- Compilation errors are the easiest to fix (just follow the error message)
- Runtime errors require careful checking (division by zero, array out of bounds)
- Logic errors are the hardest to find (use
coutor a debugger) - Debugging techniques:
- Use
coutto output key variable values - Use the IDE debugger to set breakpoints and step through
- Treat warnings as errors (
-Wall -Wextra -Werror)
- Use
📝 Exercises
- Basic (Difficulty ⭐): Fix the following program (it has 5 bugs):
#include <iostream>
int main() {
int x = 5
int y = 10;
if (x = y) {
std::cout << "x and y are equal" << std::endl;
}
for (int i = 0; i <= 10; i++) {
std::cout << i << " ";
}
return 0;
}
-
Intermediate (Difficulty ⭐⭐): Write a program that lets the user enter 10 integers and finds the maximum and minimum values.
-
Use
coutdebugging to output variable values at each loop iteration -
Intentionally introduce a bug (e.g., using a wrong value to initialize the maximum), then use debugging to find the problem
-
Challenge (Difficulty ⭐⭐⭐): Learn to use the VS Code debugger:
-
Set breakpoints in the number guessing game code from
practice-branch-loop.md -
Press
F5to start debugging -
Use "step through" to run line by line, observing the values of
secretNumber,guess, andattempts -
Take a screenshot and show me!
- Three types of errors: compilation errors, runtime errors, logic errors
- Compilation errors are the easiest to fix — just follow the error message
- Runtime errors: division by zero, array out of bounds
- Logic errors are the hardest to find — use cout or a debugger to investigate step by step
- Compile with -Wall -Wextra to enable all warnings
8. 🚀 Next Steps
Congratulations! You've completed all the lessons in Phase 1 (Introduction). You've now mastered the basics of C++ — variables, data types, operators, conditional statements, loops, and debugging.
Next, we'll enter Phase 2 (Functions), learning how to package code into reusable modules to make your programs cleaner and easier to maintain!