← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 3 of 17

C++ Debugging Techniques

Debugging a C++ program combines print-statement tracing, compiler warnings, assert() checks, and a proper debugger like GDB to locate and understand the cause of unexpected behavior.

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

cpp
#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;
}

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

cpp
#include <iostream>

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

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

cpp
#include <iostream>
#include <cassert>

int main() {
	int age = 25;
	assert(age >= 0);
	std::cout << "Assertion passed" << std::endl;
	return 0;
}

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

cpp
#include <iostream>

int main() {
	int total = 0;
	for (int i = 0; i < 3; i++) {
		total += i;
	}
	std::cout << total << std::endl;
	return 0;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.