MISRA C:2012 Rule 2.2

There shall be no dead code

Description

Rule Definition

There shall be no dead code.

Rationale

If an operation is reachable but removing the operation does not affect program behavior, the operation constitutes dead code.

The presence of dead code can indicate an error in the program logic. Because a compiler can remove dead code, its presence can cause confusion for code reviewers.

Operations involving language extensions such as __asm ( "NOP" ); are not considered dead code.

Polyspace Implementation

Polyspace® Bug Finder™ detects useless write operations during analysis.

Polyspace Code Prover™ does not detect useless write operations. For instance, if you assign a value to a local variable but do not read it later, Polyspace Code Prover does not detect this useless assignment. Use Polyspace Bug Finder to detect such useless write operations.

In Code Prover, you can also see a difference in results based on your choice for the option . See Check for Coding Standard Violations.

Troubleshooting

If you expect a rule violation but do not see it, refer to Coding Standard Violations Not Displayed.

Examples

expand all

extern volatile unsigned int v;
extern char *p;

void f ( void ) {
    unsigned int x;


    ( void ) v;      /* Compliant - Exception*/
    ( int ) v;       /* Non-compliant  */
    v >> 3;          /* Non-compliant  */

    x = 3;           /* Non-compliant - Detected in Bug Finder only */

    *p++;            /* Non-compliant  */
    ( *p )++;        /* Compliant  */
}

In this example, the rule is violated when an operation is performed on a variable, but the result of that operation is not used. For instance,

  • The operations (int) and >> on the variable v are redundant because the results are not used.

  • The operation = is redundant because the local variable x is not read after the operation.

  • The operation * on p++ is redundant because the result is not used.

The rule is not violated when:

  • A variable is cast to void. The cast indicates that you are intentionally not using the value.

  • The result of an operation is used. For instance, the operation * on p is not redundant, because *p is incremented.

void g ( void ) {
               /* Compliant  */
}

void h ( void) {
     g( );     /* Non-compliant */
}

In this example, g is an empty function. Though the function itself does not violate the rule, a call to the function violates the rule.

Check Information

Group: Unused Code
Category: Required
AGC Category: Required
Introduced in R2014b