Notes – What is Error in C++ and Types of Error
In C++, an error is a problem in the code that prevents the program from running correctly or compiling successfully.
Errors can occur due to syntax mistakes, wrong logic, or runtime issues.
Types of Errors in C++
C++ errors can be broadly divided into the following main types:
Syntax Error
- Occurs when the rules of the language are broken.
- Detected at compile time.
- Prevents code from compiling.
Examples:
cout << "Hello" // Missing semicolon
int 4number; // Invalid variable name
Semantic Error
- Code is syntactically correct but meaning is incorrect.
- Compiler doesn’t show an error, but the program doesn’t behave as expected.
Example:
int a = 10, b = 0;
int c = a / b; // Dividing by zero is logically wrong
Logical Error
- Occurs when the program runs but gives wrong output.
- Hard to detect, since the program still runs.
- Caused by wrong logic or formula.
Example:
int area = length + breadth; // Should be length * breadth
Runtime Error
- Happens while the program is running.
- Usually caused by illegal operations, like accessing invalid memory or dividing by zero.
Example:
int arr[5];
arr[10] = 100; // Accessing out of bounds index
Linker Error
- Occurs when the compiler cannot link function calls with their definitions.
- Often caused by missing function definitions or incorrect file linking.
Example:
void display(); // Function declared
// No definition given for display()
Summary Table
| Error Type | When It Occurs | Detected By | Example |
|---|---|---|---|
| Syntax Error | Compile Time | Compiler | Missing semicolon |
| Semantic Error | Compile Time | Compiler | Dividing by zero |
| Logical Error | Runtime (Visible) | Programmer | Wrong formula |
| Runtime Error | During Execution | System/Compiler | Array index out of range |
| Linker Error | After Compilation | Linker | Missing function definition |
Summary Points
- Errors stop your code from working correctly.
- Knowing error types helps in debugging faster.
- Always fix syntax and linker errors first, then handle logic and runtime issues.
