A program does exactly what you wrote, not what you meant. When the two differ,
there is a bug, and finding it is called debugging. Every programmer
spends a good part of their time on it — the difference between a beginner and
an expert is not that the expert writes no bugs, but that they have a method for
finding them. This lesson gives you that method. Functions help: a bug is far
easier to find in a ten-line function than in a hundred-line main.
Three kinds of trouble
| What you see | What it is | Where to look |
|---|---|---|
| The program doesn't build: the compiler prints errors | a compile error: the code breaks the rules of C++ | the line the message names, or the line just above it |
| It builds, but stops in the middle; the judge says Runtime error | a crash: an index outside the vector, a division by zero | the indexes and the divisors, on the input that crashed |
| It runs and finishes, but the answer is wrong | a logic error: the code says something different from what you meant | anywhere — this is what the rest of the lesson is about |
Reading a compiler error
Compiler messages look frightening, but they all have the same shape: the
file, the line and the column, the word error, and what went wrong.
Here is a function with a missing semicolon, and what g++ says about it:
In the file, the function sits below #include, using namespace std; and an
empty line, so is line 5 and the is line 6. The message names
line 6, the , because that is where the compiler
that something was missing. The semicolon belongs at the end of line 5. When a
message doesn't make sense for the line it names, look at the line above.