divide by zero - c programming

柔情痞子 提交于 2019-11-28 13:28:13

You can't rely on this "working" (i.e. doing the same thing all the time, portably) at all, it's undefined behavior in C for the second case, and also for the first if your implementation doesn't define __STDC_IEC_559__ (this is, I believe, rare these days).

C99, §6.5.5/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.

The fact you're getting a "Not a Number" in one case and and not in the other is that one is done in floating-point arithmetic, where, on your implementation (conforming to IEEE 754 division by zero semantics), 0/0 gives a NaN.

In the second case, you're using integer arithmetic – undefined behavior, there's no predicting what will happen.

The reason you don't get an exception or error is because for a double, infinity and NaN are defined (see IEEE floating point) but when you try the same for integer, you'll get an error because NaN/Infinity aren't defined

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

Non-floating point types like int do not have those special values defined and so the run-time is being terminated due to un-handled error.

This is not C-specific, you will see a very similar (if not the same) behavior in other languages simply because this functionality is down to hardware.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!