Types Of Errors In C++ Programming - Programming Basics - Bilal Ahmad Khan AKA Mr. BILRED
Types Of Errors In C++ Programming - CppNotes - Basic Knowy
Introduction
Errors in C++ programming, Aah! I guess every programmer faces them. But, There
are some types of errors in programming, and understanding different types of
errors might help in debugging and improving code efficiency.
In C++, errors can be classified into three main types:
- Syntax Errors
(Compile-Time Errors)
- Logical Errors
- Runtime Errors (Exceptions)
We’ll go through each of them one by one!
1.
Syntax Errors (Compile-Time Errors)
A syntax error
occurs when the code does not follow the rules of the C++ language. These
errors are detected by the compiler before the program runs
#include
<iostream>
using
namespace std;
int
main() {
cout
<< "Hello,
World!" // Missing semicolon
return
0;
}
Error: expected ';' before 'return'
Fix: Add a semicolon at the end of the cout statement.
2.
Logical Errors
A
logical
error happens when the program runs but produces incorrect
results. These errors do not generate compiler warnings, making them harder to
detect.
#include
<iostream>
using
namespace std;
int
main() {
int
num1 = 5,
num2 = 10;
int
sum = num1 -
num2; // ❌Wrong
operator used (should be +)
cout <<
"Sum: "
<< sum <<
endl; // Output: Sum: -5 (Incorrect)
return
0;
}
Error: The program runs successfully but gives an
incorrect result.
Fix:
Change num1 - num2
to num1
+ num2
.
3.
Runtime Errors (Exceptions)
A runtime error
occurs during program execution. These errors can cause the program to crash
#include
<iostream>
using
namespace std;
int
main() {
int
a =
10, b
= 0;
cout
<< "Result:
" <<
(a /
b); // ❌
Division by zero
return
0;
}
Error:
Floating-point exception (crash).
Fix: Check for zero before
performing division.
Example 2: Out-of-Bounds Array Access
#include
<iostream>
using
namespace std;
int
main() {
int
arr[3]
= {1,
2, 3};
cout <<
arr[5];
// Accessing an invalid index
return
0;
}
Error: Undefined behavior, might
crash or give garbage value.
Fix: Ensure the index is within
array bounds
Other
Types of Errors
4.
Semantic Errors
Semantic
errors occur when the code is logically correct but does not do what was
intended.
#include
<iostream>
using
namespace std;
int
main() {
int
x =
5;
cout
<< "Double
of x is: " <<
x *
x <<
endl;
// Should be x * 2
return
0;
}
Error: The
code compiles, but the logic is wrong.
Fix: cout << "Double of x is: " << x * 2 << endl;
5.
Linker Errors
Linker errors
occur when the compiler cannot link referenced functions or libraries.
#include
<iostream>
using
namespace std;
void
show();
// Function declared but not defined
int
main() {
show();
// Linker error: Undefined reference to 'show'
return
0;
}
A Simple Encoded Note for nerds,
but with a good heart…
SSBqdXN0IHdhbm5hIGNvbnZlcnQgbXkgU1RSRVNTIGludG8gUFJPRFVDVElWSVRZLCBTbyBJIG1hZGUgdGhpcywgTUFZQkU=
----------------------------------------------------------------------
Comments
Post a Comment