EpiX
EpiX

Reputation: 1409

is if(float > int) really if(float > (float)int)?

is

 if(float > int)

really just

 if(float > (float)int)

I was doing so research and it seems like it costs a lot to do float to int and int to float casts. I have a lot of float/int comparisons.

Just a quick question

Upvotes: 0

Views: 279

Answers (2)

user541686
user541686

Reputation: 210725

Yes!

They're the same thing.

There's no instruction to directly compare a floating-point to an integer, so it first casts the integer to float.


However:

Be careful: That does not mean that the int-to-float conversion is lossless. It still can lose some information, so this code:

(int)(float)integer == integer

doesn't always evaluate to true! (Try it with int.MaxValue to see. Ditto with double/long.)

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1502806

Yes. There's no >(float, int) operator - just >(int, int) and >(float, float). So the compiler calls the latter operator by converting the second operand to float. See section 7.3.6.2 of the C# spec for more details:

Binary numeric promotion occurs for the operands of the predefined +, -, *, / %, &, |, ^, ==, !=, >, <, >= and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type which, in case of the nonrelational operators, also becomes the result type of the operation.

(It then lists the steps involved.)

Are you sure that the int to float conversion is taking a lot of time though? It should be pretty cheap.

Upvotes: 3

Related Questions