Division by Zero in C++

What happens if I divide by zero in my code? Will it crash my program or give me an error?

Dividing by zero in C++ can lead to different behaviors depending on whether you're working with integer or floating-point numbers.

Integer Division by Zero

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

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 zero
  • inf (negative infinity) when dividing a negative number by zero
  • nan (not a number) when dividing zero by zero

In 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

Numbers

An introduction to the different types of numbers in C++, and how we can do basic math operations on them.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Pre vs Post Increment
Why does Level++ and ++Level do the same thing? When should I use one over the other?
Rounding Floating Point Numbers
How do I round floating point numbers to the nearest integer? For example, if I want 2.7 to become 3?
Integer Overflow in C++
What happens if I try to store a really big number like 999,999,999,999 in an int? Will it give me an error?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant