Dividing by zero in C++ can lead to different behaviors depending on whether you're working with integer or floating-point numbers.
When you divide an integer by zero, your program will crash due to a hardware exception. This is actually good - it helps you catch errors early:
#include <iostream>
using namespace std;
int main() {
int health{100};
int divisor{0};
// Program crashes here
int result{health / divisor};
cout << "This line never executes";
}
Arithmetic exception: divide by zero
Floating-point division by zero behaves differently - instead of crashing, it gives you special values:
#include <iostream>
using namespace std;
int main() {
float health{100.0f};
float divisor{0.0f};
float result{health / divisor};
cout << "Result: " << result << "\n";
float negativeHealth{-100.0f};
float negativeResult{
negativeHealth / divisor};
cout << "Negative result: "
<< negativeResult << "\n";
float zero{0.0f};
float undefined{zero / zero};
cout << "Zero divided by zero: " << undefined;
}
Result: inf
Negative result: -inf
Zero divided by zero: nan
The program produces three special values:
inf
(infinity) when dividing a positive number by zeroinf
(negative infinity) when dividing a negative number by zeronan
(not a number) when dividing zero by zeroIn real programs, you should check for division by zero before performing the operation. Here's a safer way:
#include <iostream>
using namespace std;
float safeDivide(float numerator,
float divisor) {
if (divisor == 0.0f) {
cout << "Warning: Division by zero!\n";
return 0.0f; // Or another appropriate value
}
return numerator / divisor;
}
int main() {
float health{100.0f};
float divisor{0.0f};
float result{safeDivide(health, divisor)};
cout << "Result: " << result << "\n";
}
Warning: Division by zero!
Result: 0
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the different types of numbers in C++, and how we can do basic math operations on them.