Best practice for calculating function return value

Often I created functions in C that checks some parameters and returns an error code.

What is the best way to stop checking values ​​when an error is detected?

First example:

ErrorCode_e myCheckFunction( some params )
{
  ErrorCode_e error = CHECK_FAILED;

  if( foo == bar )
  {
     if( foo_1 == bar_1 )
     {
        if( foo_2 == bar_2 )
        {
           error = CHECK_SUCCESS;
        }
     }
  }

  return error;
}

Second example:

ErrorCode_e myCheckFunction( some params )
{
  if( foo != bar )
  {
     return CHECK_FAILED;
  }

  if( foo_1 != bar_1 )
  {
     return CHECK_FAILED;
  }

  if( foo_2 != bar_2 )
  {
     return CHECK_SUCCESS;
  }
}

I prefer the first approach because I read that MISRA rules avoid the multiple return statement.

What is the best approach?

+4
source share
4 answers

-, , , . , , , .

, MISRA-C , MISRA-C. , , , , . , 10 . 10 if-, .

MISRA, . MISRA-C IEC 61508 . , , (IEC 61508: 7 C.2.9), 1979 .

- MISRA-C, IEC 61508 ( ISO 26262) ( ), 1979 .

MISRA .

+11

, ( ) () ( , ).

: " " . / , - - .
" " , . , " , , ". : ", , - , ". !

... , , , , .

+2

Lundins, , - :

ErrorCode_e myCheckFunction( some params )
{
  ErrorCode_e error = CHECK_FAILED;

  if( foo != bar )
  {
     error = CHECK_FAILED;
  }
  else if( foo_1 != bar_1 )
  {
     error = CHECK_FAILED;
  }
  else if( foo_2 != bar_2 )
  {
     error = CHECK_SUCCESS;
  }
  else
  {
     // else (even empty) is required by MISRA after else-if
  }
  return error;
}

, :

ErrorCode_e myCheckFunction( some params )
{
  ErrorCode_e error = CHECK_FAILED;

  if( (foo == bar) && (foo_1 == bar_1) && (foo_2 != bar_2) )
  {
     error = CHECK_SUCCESS;
  }

  return error;
}

, :

ErrorCode_e myCheckFunction( some params )
{
  return ( (foo == bar) && (foo_1 == bar_1) && (foo_2 != bar_2) )
      ? CHECK_SUCCESS : CHECK_FAILED;
}
+2

, , - goto error_exit.

, .

1 - , . , , .

2 - , . , , , , , .

3 - . . , . , , . .

4 - . , , .

5 - . , . , .

The goto error_exit method is the one that I prefer. It saves one entry point. and the exit principle is practically intact, without introducing artificial nesting for memory allocation errors that are less likely than computer violations.

+1
source

Source: https://habr.com/ru/post/1671344/


All Articles