int or long int VS. float or double

Discussion in 'Mac Programming' started by Darkroom, Jul 16, 2008.

  1. Darkroom Guest


    Dec 15, 2006
    Montréal, Canada
    i've seen lots of sample code where something like this is written:

    double seconds = 8455944321;
    while i'm under the impression that it should be

    long int seconds = 8455944321;
    it seems very possible use float or double where it "should" be int or long int and everything is fine without unexpected results... (can't do the inverse, though).

    are there any potential downfalls to declaring a variable as a float when it's really an int? does it make the app slower or use up memory? anything damaging at all?
  2. ghayenga macrumors regular

    Jun 18, 2008

    Since doubles and floats are stored as binary there are some numbers that when assigned to a float or double do not equal the exact integer value.


    float x = 3777777; //this isn't one of them it's just an example.
    int y = 3777777;

    if (x == y)
    //This line won't get called because x actually equals 377776.9999999
    //since it was stored as a float

    Not common, but it has bit me on occasion.
  3. Darkroom thread starter Guest


    Dec 15, 2006
    Montréal, Canada
  4. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    Another practical reason one might do this is that the value needs to be passed to an API or system function that takes a float or double. Obviously in this case passing in an int will not work out, and depending on whether it's a message pass in Objective-C or a system call the call will either fail, or the memory will be treated as a float or double instead of an int or long int, and bad things will happen.

    A cast will not occur, and instead the 2's complement integer value will be interpreted as an IEEE-754 floating point value, which will surely not behave as desired. There are very few cases where you want to do something like this (explicitly treat integer memory as a float and vice versa). One fun case is this:

    It's a discussion of a square root/inverse square root that was used in the Quake source.


Share This Page