C++ · Module 1 · Lesson 61 min read

Understanding Errors

Four kinds of errors

TypeWhenExample
Syntax / compile errorcompilingmissing ;, misspelled keyword, wrong type
Link errorlinkingfunction declared but never defined
Runtime errorrunningdivision by zero, invalid memory access, crash
Logic errorrunningprogram runs but gives the wrong answer

Reading a compiler error

CSS
main.cpp:5:31: error: expected ';' before 'return'
  • main.cpp file · 5 line · 31 column · then the message
  • ✅ Fix the first error first: one mistake can cause many later errors
  • The real problem is often on the line before the reported one

Common compile errors

Message (g++)Usual cause
expected ';' before ...missing semicolon
'cout' was not declared in this scopemissing #include <iostream> or std::
'x' was not declared in this scopetypo or variable used outside its scope
invalid conversion from ... to ...wrong type
no matching function for call to ...wrong arguments

undefined reference to 'calculate(int)' → you declared calculate but forgot the body, or forgot to compile/link the file containing it.

Warnings

Warnings are not errors, but they usually point at real bugs:

  • unused variable
  • comparison of integer expressions of different signedness
  • control reaches end of non-void function (forgot to return)

Debugging logic errors

  1. Print intermediate values (std::cerr << "x=" << x << '\n';)
  2. Use a debugger (gdb, Visual Studio, VS Code): breakpoints, step through, watch variables
  3. Test with small, known inputs
  4. Explain the code line by line (rubber-duck debugging 🦆)

Example

C++
#include <iostream>

// Logic error example: average of three marks
double average_wrong(int a, int b, int c) {
    return (a + b + c) / 3;          // integer division! decimals are lost
}

double average_right(int a, int b, int c) {
    return (a + b + c) / 3.0;        // 3.0 makes it floating-point division
}

int main() {
    std::cout << "Wrong average: " << average_wrong(80, 75, 92) << '\n';
    std::cout << "Right average: " << average_right(80, 75, 92) << '\n';

    // Debug print to std::cerr (the error stream) to inspect a value
    int sum = 80 + 75 + 92;
    std::cerr << "[debug] sum = " << sum << '\n';
    return 0;
}

/* Output:
Wrong average: 82
Right average: 82.3333
*/