0

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.

tryanderror
  • 153
  • 1
  • 9
  • 2
    Why do you think `1.0f` and above is True? In C, `0` is `false`, and ***any*** non-zero value (including negative values) is `true`. In the case of a `float`, any non-zero value, including tiny decimals, such as `0.002`, is still `true`. – abelenky Jun 23 '22 at 13:08
  • 2
    *I do see a problem here* What problem exactly do you see here? There is no error from C standard view. (Assuming `FIXED_ARRAY_ENTRY` is a valid index value.) – Gerhardh Jun 23 '22 at 13:11
  • Did you enable the MISRA rule checking? Will it report other violations that you introduce? – Weather Vane Jun 23 '22 at 13:54

1 Answers1

4

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396