C++ Errors
Errors
Even experienced C++ developers make mistakes. The key is learning how to spot and fix them!
These pages cover common errors and helpful debugging tips to help you understand what's going wrong and how to fix it.
Common Compile-Time Errors
These are mistakes that stop your program from compiling:
1) Missing semicolon:
2) Using undeclared variables:
3) Mismatched types (e.g. trying to assign a string
to an int
):
Common Runtime Errors
These happen when the program compiles but crashes or behaves unexpectedly.
1) Dividing by zero:
int a = 10;
int b = 0;
int result = a / b;
// not possible
cout << result;
2) Accessing out-of-bounds array elements:
int numbers[3] = {1, 2, 3};
cout << numbers[8]; // element
does not exist
3) Using deleted memory (dangling pointer):
int* ptr = new int(10);
delete ptr;
cout << *ptr;
// invalid
Good Habits to Avoid Errors
- Always initialize your variables
- Use meaningful variable names
- Keep your code clean and use indentation to stay organized
- Keep functions short and focused
- Check if loops or conditions are running as expected
- Read error messages carefully - they often tell you exactly where the problem is
In the next chapter, you will learn how to debug your code - how to find and fix bugs/errors in your program.