Error Types and Causes
Syntax Errors
Syntax errors occur when code violates C++ language grammar rules. These are the most common and easiest to detect.
Common Syntax Error Examples
// Missing semicolon
int x = 5 // Error: expected ';' at end of statement
// Mismatched brackets
void function() {
int x = 10;
if (x > 0 { // Error: missing closing bracket
// Code block
}
}
Semantic Errors
Semantic errors involve incorrect logic or type mismatches that the compiler can detect.
Type Mismatch Example
int main() {
std::string name = 42; // Error: cannot convert int to string
return 0;
}
Linker Errors
Linker errors happen when the compiler cannot resolve references between different code modules.
Linker Error Types
Error Type |
Description |
Example |
Undefined Reference |
Missing function definition |
Calling an undeclared function |
Multiple Definition |
Duplicate symbol declarations |
Defining a function in multiple files |
graph TD
A[Memory-Related Errors] --> B[Uninitialized Variables]
A --> C[Pointer Misuse]
A --> D[Memory Allocation Issues]
Pointer Error Example
int* ptr; // Uninitialized pointer
*ptr = 10; // Undefined behavior
Template and Generic Programming Errors
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
// Error if '+' operator not defined for custom type
MyCustomType result = add(obj1, obj2);
return 0;
}
Compilation Warning Categories
Warning Level |
Description |
Recommended Action |
Low |
Minor issues |
Optional review |
Medium |
Potential problems |
Investigate |
High |
Likely bugs |
Immediate fix |
Best Practices with LabEx
- Always compile with warning flags (
-Wall -Wextra
)
- Read error messages carefully
- Use modern C++ features and smart pointers
- Regularly update compiler and tools