Divide by zero - c programming

I have a question about the following code:

int main { double x = 0; double y = 0/x; if(y==1) {.....} .... .... return 0; } 

When I run the code on my computer, I have no run-time error, and I see this y = -nan(0x8000000000000) . Why is this not a runtime error for division by zero?

Also, when I change the first line to int x = 0; now there is a runtime error. What is the difference?

+7
source share
3 answers

You cannot rely on this โ€œworkingโ€ one (i.e. doing the same thing all the time, portable) in general, this behavior is undefined in C for the second case, and also for the first, if your implementation doesn't define __STDC_IEC_559__ (this, I find it rarely happens these days).

C99, ยง6.5.5 / 5

The result of the operator / is quotient of dividing 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 fact that you get "not a number" in one case, and not in the other, is that one is performed in floating point arithmetic, where on your implementation (in accordance with the division of IEEE 754 by zero semantics), 0/0 gives NaN.

In the second case, you use integer arithmetic - undefined, does not predict what will happen.

+13
source

The reason you are not getting an exception or error is because double, infinity and NaN are defined (see IEEE floating point ), but when you try the same thing for integer, you get an error because NaN / Infinity not defined

+9
source

This is because the IEEE 754 standard defines special values โ€‹โ€‹for positive and negative infinity along with "not a number" for floating point values.

Non-floating point types, such as int , do not have specific special values, so the runtime is interrupted due to an error without processing.

This is not C-specific, you will see very similar (if not the same) behavior in other languages โ€‹โ€‹simply because this functionality does not match the hardware.

+4
source

All Articles