Cast to int vs floor Cast to int vs floor c c

Cast to int vs floor


Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.


As was said before, for positive numbers they are the same, but they differ for negative numbers. The rule is that int rounds towards 0, while floor rounds towards negative infinity.

floor(4.5) = (int)4.5 = 4floor(-4.5) = -5 (int)(-4.5) = -4

This being said, there is also a difference in execution time. On my system, I've timed that casting is at least 3 times faster than floor.

I have code that needs the floor operation of a limited range of values, including negative numbers. And it needs to be very efficient, so we use the following function for it:

int int_floor(double x) {     return (int)(x+100000) - 100000; }

Of course this will fail for very large values of x (you will run into some overflow issues) and for negative values below -100000, etc. But I've clocked it to be at least 3 times faster than floor, which was really critical for our application. Take it with a grain of salt, test it on your system, etc. but it's worth considering IMHO.


SO 101, do not change your question after people have replied to your question, instead write a new question.

Why do you think they will have the same result?

float foo = (int)(bar / 3.0) //will create an integer then assign it to a floatfloat foo = fabs(bar / 3.0 ) //will do the absolute value of a float divisionbar = 1.0foo1 = 0;foo2 = 0.33333...