C++ Debugging Techniques
In this page:
Print-Statement Debugging
The simplest debugging technique is inserting temporary cout statements at key points in the code to print variable values and confirm which branches of logic actually execute.
Example: Print-Statement Debugging
#include <iostream>
int main() {
int x = 5;
std::cout << "x is: " << x << std::endl;
if (x > 0) {
std::cout << "Entered positive branch" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Compiler Warnings
Compiling with warning flags like -Wall catches many bugs before the program even runs, flagging issues like uninitialized variables, comparisons that are always true, or unused values.
Example: Compiler Warnings
#include <iostream>
int main() {
int x;
x = 5;
std::cout << x << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using assert()
The assert() macro from <cassert> checks that a condition is true at runtime, immediately terminating the program with a clear error message if it's ever false, catching bugs as close as possible to their source.
Example: Using assert()
#include <iostream>
#include <cassert>
int main() {
int age = 25;
assert(age >= 0);
std::cout << "Assertion passed" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Tracing with a Debugger
A debugger like GDB lets a program be paused at a specific line (a breakpoint), its variables inspected, and execution stepped through one line at a time, offering far more insight than print statements alone.
Example: Tracing with a Debugger
#include <iostream>
int main() {
int total = 0;
for (int i = 0; i < 3; i++) {
total += i;
}
std::cout << total << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Common Bug Categories to Watch For
Common C++ bugs include off-by-one errors in loops, uninitialized variables, dangling pointers after delete, and comparing floating-point numbers for exact equality, all worth checking first when debugging.
Example: Common Bug Categories to Watch For
#include <iostream>
int main() {
int arr[3] = {1, 2, 3};
for (int i = 0; i < 3; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 17 topics to unlock
0/17 topics done
Complete these topics first:
- C++ vs C Differences
- C++ Interview Questions
- C++ Debugging Techniques
- C++ Input Validation
- C++ Namespaces
- C++ Header Files
- C++ Multi-file Programming
- C++ static_cast
- C++ dynamic_cast
- C++ const_cast
- C++ reinterpret_cast
- C++ Threads (std::thread)
- C++ Mutex & Locks
- C++ async & future
- C++ Mini Project — Calculator
- C++ Mini Project — Student Management
- C++ Interview Questions Advanced