Home > Blockchain >  Evaluation of floats in if condition
Evaluation of floats in if condition

Time:06-24

I was debbugging some code and found an interesting if condition which was not marked as an error while using pc-lint with MISRA2004.

static float32_t float_values[10u] = {0.0f};

if (float_values[FIXED_ARRAY_ENTRY])
{
   /* Do stuff */
}

I do see a problem here, but this line actualy did what it should do. So my question is about understanding how the if statement evaluation works. My understanding would be, that the compiler will cast the condition content to an int value and if the float value is 1.0f or above, the code just works as intended.

And my second question would be, why did pc-lint not find this error.

CodePudding user response:

MISRA C has two rules that may apply:

  • Conditions in if statements should be "essentially boolean". Meaning they need to be explicit and self-documenting. if(ptr) is not compliant, if(ptr != NULL) is compliant.
  • MISRA forbids comparing floats for equality in several contexts, because of floating point inaccuracies.

This code certainly violates the first rule, but not really the second since there is no explicit use of == or !=.

My understanding would be, that the compiler will cast the condition content to an int value and if the float value is 1.0f or above, the code just works as intended.

No that's wrong. if statement conditions in C accept any scalar, that is: integers, floats and pointers. It evaluates to true if the scalar is non-zero/non-null, otherwise false. if(0.1f) evaluates as true, if((int)0.1f) evaluates as false.

And my second question would be, why did pc-lint not find this error.

Because the error you claim is there, isn't there. The question is rather why PC Lint didn't find the MISRA violation of not passing a type which is "essentially boolean" to if. The answer is: because PC Lint is really bad.

  • Related