Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Darkroom

Guest
Original poster
Dec 15, 2006
2,445
0
Montréal, Canada
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?
 

ghayenga

macrumors regular
Jun 18, 2008
190
0
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?

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.
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
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:
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.