Course contentsShow
← C
Lesson 835 of 1,21911. The Preprocessor and BuildFree lesson

Setting conditional breakpoints

Setting conditional breakpoints

What you'll learn: How to tell GDB to pause your program only when a specific variable meets a certain criteria, saving you from clicking "next" hundreds of times.

The "Stop if" Logic

Imagine you are a quality control inspector on a conveyor belt that processes 10,000 apples. You know there is a single bruised apple, but you don't want to pick up and inspect every single one. Instead, you tell your assistant: "Only stop the belt if the apple is brown."

In standard debugging, a regular breakpoint is like stopping the belt for every single apple. It’s exhausting. A conditional breakpoint allows you to stay hands-off until a specific logical condition is met, such as i == 500 or error_code != 0.

How to Set the Condition

In GDB, you add a condition to a breakpoint using the if keyword. You can do this when you first create the breakpoint, or add it to an existing one.

Suppose you have a loop that crashes only on the 75th iteration. Instead of hitting continue 74 times, you would do this:

#include <stdio.h>

int main() {
    for (int i = 0; i < 100; i++) {
        // Imagine a complex bug that only happens when i is 75
        printf("Processing item %d\n", i);
    }
    return 0;
}

Inside GDB, you would set the breakpoint like this: break main.c:6 if i == 75

When you run the program, GDB will silently monitor the value of i. The program will run at near-full speed until the moment i equals 75, at which point the execution will pause, and you can begin your deep investigation.

Refining Existing Breakpoints

If you already have a breakpoint (let’s say it is breakpoint #1) and you realize it's triggering too often, you don't need to delete it. You can add a condition after the fact:

condition 1 i > 100 && user_id == 5

GDB uses standard C syntax for these expressions. You can use comparisons (==, !=, <, >) and logical operators (&&, ||). This turns GDB from a simple "pause" button into a surgical tool that only interrupts you when the "bruised apple" finally appears.

Key takeaway

Use break [location] if [condition] to ignore irrelevant iterations and jump straight to the moment a bug occurs.