What is the benefit of terminating if … else if constructs with an else clause?

前端 未结 12 1064
不思量自难忘°
不思量自难忘° 2020-11-27 13:37

Our organization has a required coding rule (without any explanation) that:

if … else if constructs should be terminated with an el

12条回答
  •  情话喂你
    2020-11-27 13:53

    Your company followed MISRA coding guidance. There are a few versions of these guidelines that contain this rule, but from MISRA-C:2004:

    Rule 14.10 (required): All if … else if constructs shall be terminated with an else clause.

    This rule applies whenever an if statement is followed by one or more else if statements; the final else if shall be followed by an else statement. In the case of a simple if statement then the else statement need not be included. The requirement for a final else statement is defensive programming. The else statement shall either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch statement. For example this code is a simple if statement:

    if ( x < 0 )
    {
     log_error(3);
     x = 0;
    } /* else not needed */
    

    whereas the following code demonstrates an if, else if construct

    if ( x < 0 )
    {
     log_error(3);
     x = 0;
    }
    else if ( y < 0 )
    {
     x = 3;
    }
    else /* this else clause is required, even if the */
    { /* programmer expects this will never be reached */
     /* no change in value of x */
    }
    

    In MISRA-C:2012, which supersedes the 2004 version and is the current recommendation for new projects, the same rule exists but is numbered 15.7.

    Example 1: in a single if statement programmer may need to check n number of conditions and performs single operation.

    if(condition_1 || condition_2 || ... condition_n)
    {
       //operation_1
    }
    

    In a regular usage performing a operation is not needed all the time when if is used.

    Example 2: Here programmer checks n number of conditions and performing multiple operations. In regular usage if..else if is like switch you may need to perform a operation like default. So usage else is needed as per misra standard

    if(condition_1 || condition_2 || ... condition_n)
    {
       //operation_1
    }
    else if(condition_1 || condition_2 || ... condition_n)
    {
      //operation_2
    }
    ....
    else
    {
       //default cause
    }
    

    Current and past versions of these publications are available for purchase via the MISRA webstore (via).

提交回复
热议问题