Avoiding Unnecessary Casting - 2024.2 English

MicroBlaze Processor Reference Guide (UG984)

Document ID
UG984
Release Date
2024-11-27
Version
2024.2 English

While conversions between floating-point and integer formats are supported in hardware by the FPU, when C_USE_FPU is set to 2 (Extended), it is still best to avoid them when possible.

The following not-recommended example calculates the sum of squares of the integers from 1 to 10 using floating-point representation:

float sum, t;
int i;
sum = 0.0f;
for (i = 1; i <= 10; i++) {
   t = (float)i;
   sum += t * t;
}

The above code requires a cast from an integer to a float on each loop iteration. This can be rewritten as:

float sum, t;
int i;
t = sum = 0.0f;
for(i = 1; i <= 10; i++) {
   t += 1.0f;
   sum += t * t;
}
Note: The compiler is not at liberty to perform this optimization in general, as the two code fragments above might give different results in some cases (for example, very large t).