Errors in programming are inevitable, especially when learning C++. Understanding different types of errors helps students debug code efficiently and write better programs. In C++, errors are mainly classified into three categories: Syntax Errors, Runtime Errors, and Logical Errors. Sometimes, two more types are discussed: Linker Errors and Semantic Errors (advanced).

Syntax Errors (Compile-Time Errors)

Definition

Syntax errors occur when the code violates the grammatical rules of the C++ language. The compiler cannot understand the code, so the program doesn’t even compile (no executable is produced).

Why They Happen

  • Missing semicolons, brackets, parentheses.
  • Wrong keywords (spelling mistakes).
  • Incorrect use of operators or punctuations.
  • Mismatched quotes or braces.

Common Examples (For Beginners – Class 5–10)

  1. Missing Semicolon:
    C++
     
    #include <iostream>
    int main() {
        cout << "Hello World"  // Error: Missing ;
        return 0;
    }
     
     

    Compiler message: “expected ‘;’ before ‘return'”

  2. Mismatched Braces:
    C++
     
    int main() {
        cout << "Hello";
    // Missing closing }
     
     

    Error: “expected ‘}’ at end of input”

  3. Wrong Keyword Spelling:
    C++
     
    #include <iostream>
    int mian() {  // Typo: main misspelled
        return 0;
    }
     
     

    Error: “no matching function for call” or linker error later.

Detection

  • Detected by the compiler during compilation.
  • Modern IDEs (like Code::Blocks, Dev-C++, VS Code) show red underlines instantly.

How to Fix

  • Read the compiler error message carefully – it usually points to the line number and describes the issue.
  • Check for missing punctuation around that line and above.

For Intermediate Students (Class 11–12)

  • Errors in preprocessor directives:
    C++
     
    #include <isotream>  // Wrong header name
     
     
  • Template syntax mistakes in advanced code.

For BS Level (Advanced)

  • Syntax errors in complex templates or macros.
  • Using C++20/C++23 features without enabling flags (e.g., -std=c++20 in g++).

Prevention

  • Use auto-formatters (Ctrl+Shift+I in VS Code).
  • Enable compiler warnings (-Wall -Wextra in g++).

Runtime Errors (Execution-Time Errors)

Definition

The code compiles successfully, but the program crashes or behaves abnormally while running. The error occurs during execution.

Common Causes

  • Division by zero.
  • Accessing array out of bounds.
  • Dereferencing null/invalid pointers.
  • File not found (in file handling).
  • Infinite loops consuming memory.

Examples

  1. Division by Zero (Beginner Level):
    C++
     
    #include <iostream>
    using namespace std;
    int main() {
        int a = 10, b = 0;
        cout << a / b;  // Runtime error: Divide by zero
        return 0;
    }
     
     

    Output: Program crashes or shows “Floating point exception”.

  2. Array Out of Bounds (Class 10–12):
    C++
     
    int arr[5] = {1,2,3,4,5};
    cout << arr[10];  // Undefined behavior – may crash or show garbage
     
     
  3. Null Pointer Dereference (BS Level):
    C++
     
    int* ptr = nullptr;
    cout << *ptr;  // Segmentation fault (core dumped)
     
     
  4. File Handling Runtime Error (Linking to previous topic):
    C++
     
    ifstream inFile("nonexistent.txt");
    if (!inFile) {  // Good practice to check
        cout << "File not found!";
    } else {
        // Read...
    }
     
     

Detection

  • Program crashes with messages like:
    • “Segmentation fault”
    • “Abort trap”
    • “Access violation”
  • Use debuggers (gdb, VS debugger) to step through code.

How to Fix

  • Add checks before risky operations (e.g., check if denominator != 0).
  • Use try-catch for exceptions (advanced).
  • Bounds checking with .at() in vectors instead of [].

Prevention (BS Level)

  • Use assertions (assert(condition);).
  • Enable AddressSanitizer (-fsanitize=address in g++).
  • Smart pointers (unique_ptr, shared_ptr) to avoid null dereference.

Logical Errors (Semantic Errors)

Definition

The program compiles and runs without crashing, but produces wrong output because the logic of the code is incorrect. Hardest to detect!

Common Causes

  • Wrong formula or algorithm.
  • Incorrect loop conditions.
  • Off-by-one errors.
  • Wrong variable usage.

Examples

  1. Wrong Average Calculation (Class 5–8):
    C++
     
    int a=10, b=20, c=30;
    float avg = a + b + c / 3;  // Wrong: Division first → 10
    cout << avg;  // Output: 40 (instead of 20)
     
     

    Fix: float avg = (a + b + c) / 3.0;

  2. Infinite Loop (Class 9–10):
    C++
     
    int i = 0;
    while (i < 10) {
        cout << i;
        // Forgot i++;
    }
     
     

    Program runs forever.

  3. Off-by-One in Loops (Class 11–12):
    C++
     
    for(int i=1; i<=10; i++) {
        cout << i;  // Prints 1 to 10 → correct
    }
    // But if condition i<10 → prints 1 to 9 (missing 10)
     
     
  4. Student Record System Logical Error (BS Level – Linking to previous):
    C++
     
    // In search function, returning wrong position due to wrong calculation
    pos += sizeof(Student);  // Correct
    // If someone writes pos++ → wrong position for large structs
     
     

Detection

  • No compiler help – you must test with sample inputs.
  • Compare actual output vs expected output.
  • Use print statements (debug cout) to trace variables.
  • Write test cases.

How to Fix

  • Dry run the code on paper.
  • Use debuggers to watch variable values.
  • Rubber duck debugging (explain code to someone).

Prevention (BS Level)

  • Write pseudocode first.
  • Use unit testing frameworks (Google Test).
  • Code reviews.
  • Follow algorithms correctly.

Additional Types of Errors (For BS Level)

Linker Errors

  • Occur during linking phase.
  • Common: Undefined reference (function declared but not defined).
    C++
     
    void func();  // Declaration
    int main() {
        func();   // Linker error: undefined reference to `func()'
    }
     
     
  • Multiple definitions of same function.

Semantic Errors (Overlaps with Logical)

  • Code is syntactically correct but violates language rules in context (e.g., type mismatch caught by compiler in strong typing).

Summary Table (For Quick Revision on Your Website)

 
 
TypeWhen DetectedProgram Runs?ExampleDetection Tool
SyntaxCompile timeNoMissing semicolonCompiler
RuntimeExecution timeCrashesDivision by zeroOS / Debugger
LogicalExecution timeWrong outputIncorrect formulaTesting / Debugging
LinkerLinking timeNo executableUndefined referenceLinker