Dividing by zero in C

  • A+

When I compile the program:

#include <stdio.h>  int main(void) {     int x, y = 0;      x = 1 / y;     printf("x = %d/n", x);     return 0; } 

It gives "Floating point exception (core dumped)"

However, when I compile:

#include <stdio.h>  int main(void) {     double x, y = 0;      x = 1 / y;     printf("x = %f/n", x);     return 0; } 

It prints "x = inf"

Why does it return x as an infinite value if you're using double but returns an error if you're using int?


The C standard explicitly states that dividing by zero has undefined behavior for either integer or floating-point operands.

C11 6.5.5 paragraph 5:

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

Undefined behavior means that the standard says nothing about what happens. It could yield a meaningful or meaningless result, it could crash, or it could, as the standard joke goes, make demons fly out of your nose. (Of course the latter isn't going to happen, but it wouldn't violate the C standard if it did.)

Floating-point types, unlike integer types, often have special values that don't represent numbers. The IEEE floating-point standard specifies that division by zero can yield a result of Infinity, which is what your implementation is doing. There is no "Infinity" value for integers. (Note that C implementations may or may not conform to the IEEE floating-point standard.)

This question discusses the semantics of division by zero in IEEE floating-point.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: