Loading lessons...
Errors
Errors
Errors are bugs in your code, and C++ lets you find two very different kinds of them. Knowing which is which tells you whether the compiler or your own eyes should be looking for it.
Syntax errors
A syntax error is a grammar mistake: you wrote something C++ simply refuses to read. The compiler catches these for you before the program even runs.
int main() {
cout << "Hello World; // missing closing quote
return 0 // missing semicolon
}
That file will not compile. The compiler stops and points you at the broken line, so syntax errors are usually the easiest kind to fix.
Semantic errors
A semantic error means the code is legal C++, but it does the wrong thing. The compiler cannot catch it - the program runs fine, it just produces a wrong result.
int x = 5;
x = x - 1; // you meant to add 1
cout << x; // prints 4 instead of 6
No warning, no crash: the answer is simply wrong. You asked for something the computer carried out exactly - your mistake, not the compiler's.
Compiler catches, humans catch
- The compiler finds syntax errors automatically.
- Semantic errors are logical mistakes you must find by testing and debugging.
int main() {
int gates = 10;
if (gates - 1) { // wrong comparison, always true
cout << "always runs";
}
return 0;
}
gates - 1 computes a number instead of testing a condition. Small mental slips like this are semantic errors that slip right past the compiler.
TL;DR
- Errors come in two flavors: syntax and semantic.
- Syntax errors are grammar mistakes the compiler catches.
- Semantic errors compile fine but give wrong results.
- Assignment vs comparison is the classic sneaky semantic bug.
- The compiler is your friend for syntax; you must hunt semantic bugs yourself.