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

(2) 2.2 Common Compilation Errors

Error 1: Missing Semicolon

▶ Example 2: Basic programming practice (Difficulty ⭐)

TEXT 📖 Display only
#include <iostream>

int main() {
 int x = 5 // ❌ Missing semicolon
 std::cout << x << std::endl;
 return 0;
}

Output:

TEXT 📖 Display only
(Program output)

Compiler error message:

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

CPP
#include <iostream>

int main() {
 if (5 > 3 { // ❌ Missing closing parenthesis
 std::cout << "5 > 3" << std::endl;
 }
 return 0;
}

Compiler error message:

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

TEXT 📖 Display only
#include <iostream>

int main() {
 x = 5; // ❌ x is not declared
 std::cout << x << std::endl;
 return 0;
}

Compiler error message:

TEXT 📖 Display only
error: 'x' was not declared in this scope

Error 4: Type Mismatch

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

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

(2) 3.2 Common Runtime Errors

Error 1: Division by Zero

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

CPP
Floating point exception (core dumped) // Linux

Or

TEXT 📖 Display only
Process ended, exit code -1073741676 // Windows

💡 Fix: Check if the divisor is zero before performing division.


Error 2: Array Out of Bounds

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

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

CPP
#include <iostream>

int main() {
 int x; // ❌ Not initialized
 std::cout << x << std::endl; // Outputs garbage value
 return 0;
}

Run result:

TEXT 📖 Display only
32767 // Outputs garbage value (may differ each run)

💡 Fix: Initialize variables when you declare them.



4. Logic Errors (Logic Error)

(1) 4.1 Characteristics

(2) 4.2 Common Logic Errors

Error 1: Reversed Condition

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

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

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

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

  1. Set breakpoints (pause the program at a specific line)
  2. Step through (run line by line)
  3. Watch variables (see variable values in real time)

Steps:

  1. In VS Code, click the area to the left of the line number to set a breakpoint (a red dot will appear)
  2. Press F5 (or click "Run and Debug"), then select "C++ (GDB/LLDB)"
  3. The program will run and pause at the breakpoint
  4. Press F10 to step over, or F11 to step into
  5. 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:

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

Output:

TEXT 📖 Display only
Sum of array elements: 15
x not 10

Debugging process:

  1. First run: Program crashes (array out of bounds)
  1. Second run: Program outputs "x is 10" (even though x is 5)

Fixed program:

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

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

Output:

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

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

Q Why does my program compile successfully but show nothing when run?
A Two scenarios: ① On Windows, double-clicking the .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.
Q How do I configure the VS Code debugger?
A Press F5 → select "C++ (GDB/LLDB)" → VS Code auto-generates launch.json. Key things to check: whether gdb is installed, and whether the program path in launch.json is correct.
Q Why is the output order wrong when debugging with cout?
A This is a buffering issue. Use std::endl or std::flush to force-flush the buffer.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Fix the following program (it has 5 bugs):
CPP
#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;
}
  1. Intermediate (Difficulty ⭐⭐): Write a program that lets the user enter 10 integers and finds the maximum and minimum values.

  2. Use cout debugging to output variable values at each loop iteration

  3. Intentionally introduce a bug (e.g., using a wrong value to initialize the maximum), then use debugging to find the problem

  4. Challenge (Difficulty ⭐⭐⭐): Learn to use the VS Code debugger:

  5. Set breakpoints in the number guessing game code from practice-branch-loop.md

  6. Press F5 to start debugging

  7. Use "step through" to run line by line, observing the values of secretNumber, guess, and attempts

  8. Take a screenshot and show me!


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!

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%

🙏 帮我们做得更好

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

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