Main Content

MISRA C:2023 Rule 2.1

A project shall not contain unreachable code

Since R2024a

Description

Rule Definition

A project shall not contain unreachable code.

Rationale

Unless a program exhibits any undefined behavior, unreachable code cannot execute. The unreachable code cannot affect the program output. The presence of unreachable code can indicate an error in the program logic. Unreachable code that the compiler does not remove wastes resources, for example:

  • It occupies space in the target machine memory.

  • Its presence can cause a compiler to select longer, slower jump instructions when transferring control around the unreachable code.

  • Within a loop, it can prevent the entire loop from residing in an instruction cache.

Polyspace Implementation

Polyspace® reports a defect if a statement in your code is not reachable.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

enum light { red, amber, red_amber, green };

enum light next_light ( enum light color )
{
    enum light res;

    switch ( color )
    {
    case red:
        res = red_amber;
        break;
    case red_amber:
        res = green;
        break;
    case green:
        res = amber;
        break;
    case amber:
        res = red;
        break;
    default:
    {
        error_handler ();
        break;
    }
    }

    res = color;
    return res;
    res = color;     /* Non-compliant */
}

In this example, the rule is violated because there is an unreachable operation following the return statement.

Check Information

Group: Unused Code
Category: Required
AGC Category: Required

Version History

Introduced in R2024a