Understanding Errors
Four kinds of errors
| Type | When | Example |
|---|---|---|
| Syntax / compile error | compiling | missing ;, misspelled keyword, wrong type |
| Link error | linking | function declared but never defined |
| Runtime error | running | division by zero, invalid memory access, crash |
| Logic error | running | program runs but gives the wrong answer |
Reading a compiler error
main.cpp:5:31: error: expected ';' before 'return'
main.cppfile ·5line ·31column · 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 scope | missing #include <iostream> or std:: |
'x' was not declared in this scope | typo or variable used outside its scope |
invalid conversion from ... to ... | wrong type |
no matching function for call to ... | wrong arguments |
Link errors
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 variablecomparison of integer expressions of different signednesscontrol reaches end of non-void function(forgot to return)
Debugging logic errors
- Print intermediate values (
std::cerr << "x=" << x << '\n';) - Use a debugger (gdb, Visual Studio, VS Code): breakpoints, step through, watch variables
- Test with small, known inputs
- Explain the code line by line (rubber-duck debugging 🦆)
Example
#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
*/