Chapter 2. Debugging a Program

In This Chapter

  • Working with debuggers

  • Using the CodeBlocks debugger

  • Tracing through a program and in and out of functions

  • Using other debuggers

  • Getting seriously advanced debuggers

In this chapter, we talk about how you can use a debugger to track down problems and bugs in your program. Sooner or later, things don't work the way you planned them. In this case, you have several plans of attack. One plan involves a hammer and the computer, but we don't recommend that one. Instead, we suggest using a debugger to try to fix the program.

Programming with Debuggers

A debugger is a special tool that you use for tracing line by line through your program. Take a look at Listing 2-1. This is just a basic program with a main and a couple of functions that we use to demonstrate the debugger.

Example 2.1. Tracing a Simple Program

#include <iostream>

using namespace std;

int CountRabbits(int original)
{
    int result = original * 2;
    result = result + 10;
    result = result * 4;
    cout << "Calculating " << result << endl;
    return result * 10;
}

int CountAntelopes(int original)
{
    int result = original + 10;
    result = result - 2;
    cout << "Calculating " << result << endl;
return result;
}

int main()
{
    int rabbits = 5;
    int antelopes = 5;
    rabbits = CountRabbits(rabbits);
    cout << "Rabbits now at " << rabbits << endl;
    antelopes = CountAntelopes(antelopes);
    cout << "Antelopes now at " << antelopes << endl;
    // system("PAUSE"); // add this for Windows
    return 0;
}

When you type and run this program, ...

Get C++ All-In-One For Dummies®, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.