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?
-, , , . , , , .
, 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 .
, ( ) () ( , ).
: " " . / , - - ." " , . , " , , ". : ", , - , ". !
... , , , , .
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; }
, , - 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.
Source: https://habr.com/ru/post/1671344/More articles:Update TensorFlow - pythonHTML / CSS scrolling issue on mouseover - htmlUsing Plyr.io as soon as the video ends - restart the player - javascriptHow to use Kafka Connect for Cassandra without Confluent - cassandraBoostrap 4 alpha 6-row behavior inside the map - cssРазличные выходные данные при выборе из таблицы базы данных Postgresql через Perl script - databasePattern to prevent constant error checking? - cIonic2 - invisible tabs - when they are generated from the observable - tabsHow to remove view in Google Cloud Data Warehouse - google-app-enginehow to draw a line on label text in xamarin form - c #All Articles