divide by zero - c programming

15,772

Solution 1

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.

Solution 2

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

Share:
15,772
wantToLearn
Author by

wantToLearn

Updated on June 16, 2022

Comments

  • wantToLearn
    wantToLearn almost 2 years

    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?

  • Dietrich Epp
    Dietrich Epp over 11 years
    You won't always get an error for integer 0/0, it depends on the implementation.
  • Jan Hudec
    Jan Hudec over 11 years
    It should be added that the observed behaviour is defined by the platform. Ix86 happens to implement division by zero this way.
  • Dietrich Epp
    Dietrich Epp over 11 years
    This is actually wrong for most systems: C99, §F.1: "An implementation that defines __STDC_IEC_559__ shall conform to the specifications in this annex. Where a binding between the C language and IEC 60559 is indicated, the IEC60559-specified behavior is adopted by reference, unless stated otherwise." §F.3 "The +, -, *, and / operators provide the IEC 60559 add, subtract, multiply, and divide operations."
  • wantToLearn
    wantToLearn over 11 years
    but I only change the x value and not the y value. So it is like saying as before . no ?
  • 12431234123412341234123
    12431234123412341234123 almost 6 years
    @JanHudec No, the compiler can also make optimizations on the fact, that n/0 is UB. The compiler may remove this if-block n=a/b; if(!b) {/*This code will be removed*/}.