Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing by zero in C

Tags:

c

operands

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?

like image 852
Evan Waddicor Avatar asked Dec 08 '22 12:12

Evan Waddicor


1 Answers

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.

like image 76
Keith Thompson Avatar answered Dec 31 '22 02:12

Keith Thompson