﻿# Division by Zero

## Definition

Division by zero is a logic [software bug](https://pvs-studio.com/en/blog/terms/0082/) that in most cases causes a run\-time error when a number is divided by zero\.

## Program Behavior

Whether or not this run\-time error occurs depends on a number of factors: the language of the program and its development platform and the types of dividends\.

According to section 5\.6 of the C\+\+ language standard, if operators "/" and "%" have 0 as the second operand, [undefined behavior occurs](https://pvs-studio.com/en/blog/terms/0066/)\.

When trying to divide a number by an integer zero on a processor of the x86 and x86\_64 processor families, a hardware exception is generated \(by vector 0\); accordingly, a C/C\+\+ program compiled into machine code will crash when executing this operation\.

At the same time, if the zero\-variable is a real one, then, according to the IEEE 754 standard, the result is a real number "plus infinity" or "minus infinity" \(the standard also specifies that zero is a signed number\) in case of a non\-zero numerator, and a "NaN" \(_not a number_\) in case of the 0/0 indetermination \(the Microsoft Visual C\+\+ compiler returns the "indeterminate" number specific to the x86 platform\)\.

Note that the variable does not necessarily have to contain zero: it may occur as a result of rounding of values, which is called an arithmetic underflow, when the result of a rounding operation is a number whose value is under machine precision\. The result in this case is assumed as equal to 0\.

## Tracking Zero Divide Errors

Divide\-by\-zero bugs can be tracked by some compilers \(for instance, Microsoft Visual C\+\+\) and [static analyzers](https://pvs-studio.com/en/blog/terms/0074/)\.

One should be especially attentive when dividing a number by a variable which serves as a loop iterator, for one may easily forget that it should at some point go through the zero value\. Static analyzers use a special diagnostic to check that \(the [V609](https://pvs-studio.com/en/docs/warnings/v609/) diagnostic in the PVS\-Studio\)\.

## References

1. Wikipedia\. [Division by zero\.](https://en.wikipedia.org/wiki/Division_by_zero)
1. IEEE\. IEEE Standard for Floating\-Point Arithmetic \(IEEE 754\)\.
1. MSDN\. [Know Your Bugs: Three Kinds of Programming Errors](https://msdn.microsoft.com/en-us/library/s9ek7a19(v=vs.90).aspx)
1. Stack Overflow discussion\. [C\+\+ : Catch a divide by zero error](https://stackoverflow.com/questions/4747934/c-catch-a-divide-by-zero-error), [Catching exception: divide by zero](https://stackoverflow.com/questions/6121623/catching-exception-divide-by-zero)\.