Why the output of printf("%d",1/0.0) is 0?

1k views Asked by At

I use the codeblock.

When the code is:

printf("%d",1/0);

The program can not run, there is an error. But when I write this:

printf("%d",1/0.0);

The program can run,and the output is 0. I want to know why.

3

There are 3 answers

8
Yu Hao On BEST ANSWER

1/0 or 1/0.0 are both undefined behavior:

C11 ยง6.5.5 Multiplicative operators

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.

0
Eric Postpischil On

In theory, the result of 1/0.0 may be undefined in a C implementation, since it is undefined by the C standard. However, in the C implementation you use, the result is likely infinity. This is because most common C implementations use (largely) IEEE 754 for floating-point operations.

In this case, the cause of the output you see is that 1/0.0 has double type, but you are printing it with %d, which requires int type. You should print it with a specifier that accepts the double type, such as %g.

0
Shafik Yaghmour On

You are invoking undefined behavior of two different forms one by dividing by zero, the draft standard section 6.5.5 Multiplicative operators paragraph 5 says (emphasis mine):

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.

The second by using the wrong format specifier in printf, you should be using %f since the result of 1/0.0 is a double not an int. The C99 draft standard section 7.19.6.1 The fprintf function which also covers pritnf in paragraph 9 says:

If a conversion specification is invalid, the behavior is undefined.248) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Although if the implementation supports IEEE 754 floating point division by zero should result in either +/- inf. and 0/0.0 will produce a NaN. Important to note that relying on __STDC_IEC_559__ being defined may not work as I note in this comment.