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

The danger of semicolon in `#define`

The danger of semicolon in #define

What you'll learn: Why adding a semicolon to a macro definition is a common mistake that causes confusing syntax errors.

The literal copy-paster

When you use a #define directive, you are talking to the Preprocessor, not the Compiler. The Preprocessor is not very smart; it behaves like a "Find and Replace" tool. It takes your macro name and literally swaps it for whatever text follows it.

In standard C code, we are trained to end every line with a semicolon. However, if you add a semicolon to the end of a #define line, that semicolon becomes part of the replacement text. This often leads to "double semicolon" bugs that break your logic.

Seeing the invisible error

Imagine you are defining a constant for a player's starting health. Look at what happens when we reflexively add a semicolon:

#include <stdio.h>

// MISTAKE: The semicolon is now part of the definition!
#define STARTING_HEALTH 100; 

int main() {
    int current_health;

    // The Preprocessor turns this:
    // current_health = STARTING_HEALTH;
    
    // Into this (Notice the double semicolon!):
    current_health = 100;; 

    // This gets even worse in an 'if' statement:
    if (current_health > 50)
        current_health = STARTING_HEALTH; // Becomes: 100;;
    else
        current_health = 10;

    return 0;
}

Why it breaks your code

In the example above, the compiler sees current_health = 100;;. The first semicolon ends the assignment. The second semicolon is interpreted as an "empty statement."

While an extra semicolon on its own line is often harmless, it wreaks havoc in if/else structures. In C, an if statement without curly braces only controls the single next statement. Because the macro inserted two statements (the number and the extra semicolon), the else becomes detached from the if. The compiler will throw a confusing error like "else without a previous if", even though your code looks perfectly fine on the surface.

To avoid this, remember that a macro is a text substitution, not a C statement. Keep your #define lines "naked" and let the rest of your code provide the necessary punctuation.

Key takeaway

Never end a #define directive with a semicolon, as it will be literally injected into your code and cause unexpected syntax errors.