Question

This is more of an academic question than one where I'm really worried about the performance. I'm just really curious is all. I've also learned in my, admittedly limited, programming experience that the compiler is only smart about half the time.

I have a static class where a constant int is defined and I need to divide that constant by another integer. Now, I need a float value returned from that division, so I can't just leave them both as integers.

const int CONSTANTINTEGER = 69;
int integer = 0;
float floatValue = 0f;

for(integer = 0; integer < CONSTANTINTEGER; integer++) {
    float floatValue = integer / (float)CONSTANTINTEGER;
    //use floatValue for algorithm.....
}

Now, my question: Is the compiler smart enough to create a constant float in place of the (float)CONSTANTINTEGER or does it cast the integer to a float every single loop?

Was it helpful?

Solution

The language specification helps us out here. Section 7.19 of the C# 5 spec states:

A constant expression must be the null literal or a value with one of the following types: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, object, string, or any enumeration type. Only the following constructs are permitted in constant expressions:

  • ...
  • Cast expressions, provided the target type is one of the types listed above.

...

Whenever an expression fulfills the requirements listed above, the expression is evaluated at compile-time. This is true even if the expression is a sub-expression of a larger expression that contains non-constant constructs.

You can also validate this by looking at the IL, which in this case has:

IL_000a:  ldc.r4     69.

when it's loading the divisor for the division operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top