int or long int VS. float or double

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

  1. Darkroom Guest

    Darkroom

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

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

    Code:
    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

    Joined:
    Jun 18, 2008
    #2
    Precision.

    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.

    Thus

    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

    Darkroom

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

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    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:
    http://www.codemaestro.com/reviews/9

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

    -Lee
     

Share This Page