When you write a program, errors may occur at different stages. The textbook identifies four main types of errors that every programmer must understand.
1. Syntax Errors
Syntax errors occur when you violate the rules of the programming language. These are also called compile-time errors because the compiler detects them before the program runs. Common syntax errors include:
- Missing semicolons (;)
- Misspelled keywords
- Mismatched parentheses or braces
- Using a variable that has not been declared
Example in C++:
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 15;
cout << " " << (a, b) // semicolon missed
return 0;
}
Error message: error: expected ';' before '}'
The compiler tells you exactly where the problem is. To fix it, simply add the missing semicolon after the cout statement.
2. Semantic Errors
Semantic errors occur when statements are syntactically correct but have no meaning or cannot be interpreted by the compiler. These errors are often caused by using variables incorrectly or writing expressions that make no logical sense.
Example in C++:
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
a + b = c; // semantic error: cannot assign to an expression
return 0;
}
Error message: error: value required as left operand of assignment
The error occurs because a + b is an expression, not a variable, so you cannot assign a value to it.
3. Logic Errors
Logic errors occur when a program runs without producing error messages but produces incorrect results. The program compiles and executes successfully, but the output is not what you expected. These errors are the most difficult to find because the compiler does not warn you.
Example in C++:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
// logical error: semicolon after loop makes it run empty
for(i = 0; i < 3; i++);
{
cout << "loop ";
continue;
}
return 0;
}
Output: No output (the loop executes three times with an empty body)
To fix this, remove the semicolon after the for statement.
4. Run-time Errors
Run-time errors occur during program execution after successful compilation. These errors cause the program to crash or behave abnormally. Common examples include dividing by zero, accessing invalid array indices, or trying to open a file that does not exist. Run-time errors are also called bugs.
Example in C++:
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int div = x / 0; // division by zero causes run-time error
cout << "result = " << div;
return 0;
}
Result: The program terminates abnormally.