Thread: 1/0 = 1 How ?

  1. #1
    Registered User Dev's Avatar
    Join Date
    Mar 2003
    Posts
    59

    1/0 = 1 How ?

    Code:
    int main()
    {
    printf("1/0 = %d",1/0);
    }
    I compiled this program under MinGW compiler and Borland C++ 5.5 command line compiler.

    Both give warning about division by zero. But when the program is run

    The one compiled by gcc breaks and the one compiled by Borland gives output as 1.

    I don't understand this behavior.

  2. #2
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,823
    K&R says division by 0 is undefined, so the compiler can throw back whatever it wants.

  3. #3
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    Posts
    501
    in mathematics, anything divided by zero is undefined, like a vertical line whose x intercept is (2,0), if you found its slope it would be 1/0, they call this an undefined slope.

  4. #4
    Registered User Dev's Avatar
    Join Date
    Mar 2003
    Posts
    59
    My Mathematics concepts are good.

    I also know that 1/0 is undefined.

    But I am just curious about knowing this strange behavior.

    Because if I change %d to %f then I get Division by zero error and keeping it %d gives answer of 1/0 as 1.

  5. #5
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,823
    Originally posted by Govtcheez
    K&R says division by 0 is undefined, so the compiler can throw back whatever it wants.
    edit: It's worth saying that "undefined" in this case isn't the same as "undefined" in a mathematical sense. In our case, it jsut means there's no set thing it's supposed to do. The compiler can do whatever it wants.

  6. #6
    Registered /usr
    Join Date
    Aug 2001
    Location
    Newport, South Wales, UK
    Posts
    1,273
    Originally posted by Govtcheez
    K&R says division by 0 is undefined, so the compiler can throw back whatever it wants.
    But in the majority of cases (e.g. on Windows), I believe an exception is raised. Unhandled, it causes a crash.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. realloc segfaults.
    By noobcpp in forum C Programming
    Replies: 24
    Last Post: 11-26-2008, 01:16 AM
  2. Division Result
    By anirban in forum Tech Board
    Replies: 19
    Last Post: 08-13-2008, 10:21 PM