Search code examples
cmisra

MISRA violation "441 - Float cast to non-float "


I am trying to correct the MISRA violation "441 - Float cast to non-float" that is occurring with the following code:

tULong frames = (tULong)(runTimeSeconds * 40.0f);

runTimeSeconds is a float and obviously 40.0f is assigned as a float. Any ideas?


Solution

  • <math.h> has a nice family of functions that round and convert in one call. No cast needed to convert from float to tULong. Below has a (tULong) cast to handle an integer to integer conversion which may be eliminated depending on unposted issues of range and tULong details.

    #include <math.h>
    // long int lrintf(float x);
    // long long int llrint(double x);
    // 4 others
    
    tULong frames = (tULong) llrintf(runTimeSeconds * 40.0f);
    

    This rounds rather than truncates like OP's original code.