C++ Errors

❌ C++ Errors

Errors in C++ are problems in a program that prevent it from compiling correctly or behaving as expected at runtime.
Understanding errors helps you debug faster and write reliable programs.


πŸ”Ή 1. Types of Errors in C++

C++ errors are mainly classified into three types:

  1. Compile-Time Errors

  2. Run-Time Errors

  3. Logical Errors


πŸ”Ή 2. Compile-Time Errors

These errors are detected by the compiler before the program runs.

πŸ”Έ Common Causes

  • Syntax mistakes

  • Missing semicolon

  • Undeclared variables

  • Type mismatch

Example

#include <iostream>
using namespace std;
int main() {
int x = 10
cout << x;
}

❌ Error: missing ;

βœ” Fix:

int x = 10;

Example: Undeclared Variable

cout << y; // y not declared

πŸ”Ή 3. Run-Time Errors

These errors occur while the program is running and may cause the program to crash.

πŸ”Έ Common Causes

  • Division by zero

  • Accessing invalid memory

  • Dereferencing nullptr

  • File not found

Example: Division by Zero

int a = 10, b = 0;
cout << a / b; // ❌ runtime error

Example: Null Pointer

int *p = nullptr;
cout << *p; // ❌ runtime error

πŸ”Ή 4. Logical Errors

The program runs successfully, but produces incorrect output.

Example

int a = 10, b = 5;
cout << a - b; // expected sum but subtraction used

βœ” Hardest errors to find
βœ” Require careful testing and logic checking


πŸ”Ή 5. Linker Errors

Occur when the linker cannot find function definitions.

Example

void show(); // declared but not defined

int main() {
show();
}

❌ Linker error: undefined reference to show()


πŸ”Ή 6. Runtime Error Handling (Exceptions)

C++ uses exception handling to manage runtime errors.

try {
int a = 10, b = 0;
if (b == 0)
throw "Division by zero";
cout << a / b;
}
catch (const char* msg) {
cout << msg;
}

πŸ”Ή 7. Common C++ Error Messages

Error MessageMeaning
expected ';'Missing semicolon
undeclared identifierVariable not declared
segmentation faultInvalid memory access
undefined referenceMissing function definition

πŸ”Ή 8. Debugging Tips

  • Read error messages carefully

  • Fix first error first

  • Use cout to trace values

  • Use debugger (gdb / IDE debugger)

  • Enable warnings:

g++ -Wall program.cpp

πŸ”Ή 9. Preventing Errors (Best Practices)

  • Initialize variables

  • Avoid global variables

  • Use const and references

  • Check pointers before use

  • Handle file open errors

  • Use modern C++ features (smart pointers)


πŸ” Errors vs Warnings

ErrorsWarnings
Stop compilationCompilation continues
Must fixShould fix
CriticalPotential issues

πŸ“Œ Summary

  • Compile-time errors β†’ syntax & type issues

  • Run-time errors β†’ occur during execution

  • Logical errors β†’ wrong output

  • Linker errors β†’ missing definitions

  • Proper debugging reduces errors

You may also like...