Course contentsShow
← C
Lesson 1156 of 1,21916. Practice and ProjectsFree lesson

The difference between syntax and logic errors

The difference between syntax and logic errors

What you'll learn: How to distinguish between code that the computer cannot read and code that the computer follows perfectly to the wrong result.

The Grammar vs. The Recipe

Programming is a lot like writing a recipe. If you write, "Take the and flour oven put," the chef will stop and stare at you because that sentence makes no sense. This is a syntax error. However, if you write, "Put the cake in the oven for 10 hours," the chef will follow your instructions perfectly, but you will end up with a charcoal brick. This is a logic error.

Syntax Errors: The "Grammar" Police

A syntax error occurs when you break the rules of the C language. This could be a missing semicolon, a misspelled keyword like intt instead of int, or an unclosed curly brace.

The good news? The compiler acts as a safety net. It will refuse to build your program and will usually point directly to the line where you messed up. Your program never even starts running, so no damage is done.

Logic Errors: The Silent Saboteurs

Logic errors are much craftier. Your code is written perfectly according to the rules of C, so the compiler is happy. However, the instructions you gave don't actually solve the problem.

Common logic errors include using a plus sign when you meant to subtract, or accidentally telling a loop to run forever. The computer isn't "smart"—it doesn't know you wanted to calculate a discount; it only knows you told it to multiply the price by zero.

A Side-by-Side Comparison

Look at these two snippets trying to calculate the area of a square (side * side):

#include <stdio.h>

int main() {
    int side = 5;

    // SYNTAX ERROR: The compiler stops here.
    // Missing a semicolon at the end of the line.
    int area1 = side * side

    // LOGIC ERROR: The compiler is happy, but the math is wrong.
    // It adds the sides instead of multiplying them.
    int area2 = side + side; 
    
    printf("Area is: %d", area2); // Output: 10 (Wrong! Should be 25)
    
    return 0;
}

In the first case, the program won't run at all. In the second case, the program runs perfectly, but it gives you the wrong answer. Debugging logic errors is the real "detective work" of programming because you have to trace your own thinking to find the flaw.

Key takeaway

Syntax errors are broken rules that prevent the program from starting; logic errors are valid rules that produce the wrong results.