1

I am trying to get rid of rule 15.5 from my code. This is basically because of multiple returns in the function.

Code looks like:

int32_t
do_test(int32_t array[])
{  
    for(int32_t i=0; i < VAL; i++)
    {
      if(array[i] == 2) {
        return 1;
      } 
    }
    return 0;
}

I have tried with a temp variable which store the return value and returning this variable at the end. But that didnt work.

Any suggestions ?

Salim
  • 373
  • 1
  • 9
  • 19
  • 1
    You need to use a temp variable which stores the return value and return this variable at the end. Because that does work. If you don't do it wrong. – user253751 Nov 23 '17 at 04:32
  • Could you show us your failed temp variable attempt? – jwodder Nov 23 '17 at 04:33
  • int32_t do_test(const int8_t array[]) { int32_t temp; for(int32_t i=0; i < VAL; i++) { if(array[i] == 2) { temp = 1; } } temp = 0; return temp; } I tried like this. but here the for loop will execute completely and temp has the wrong value at the end – Salim Nov 23 '17 at 04:41
  • That's a rule that doesn't automatically enhance the reliability or readability of programs. – Jonathan Leffler Nov 23 '17 at 04:55
  • @JonathanLeffler most of the misra rules make the code worse IMO – M.M Nov 23 '17 at 05:05
  • This is a defect in MISRA-C, see the linked duplicate. Basically it is garbage inherited from IEC 61508. – Lundin Nov 24 '17 at 10:42

1 Answers1

2

You need to store a temp variable and to break the loop

int32_t
do_test(int32_t array[])
{
    int32_t result = 0;  
    for(int32_t i=0; i < VAL; i++)
    {
      if(array[i] == 2) {
        result = 1;
        break; // !!
      } 
    }
    return result;
}
Déjà vu
  • 28,223
  • 6
  • 72
  • 100