Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

floating point - divide by zero - c programming

I have a question about the next code:

int main { 
double x = 0;
double y = 0/x;

if(y==1) {.....}
....
....
return 0;
}

When I run the code on my computer, I get no runtime error and I see that y = -nan(0x8000000000000). Why it is not a runtime error to divide by zero?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...