Numbers

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?

3D art showing a character using an abacus

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

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved