主要内容

MISRA C:2012 Rule 2.1

R2026b

A project shall not contain unreachable code

描述

A project shall not contain unreachable code 1 .

理由

除非程序表现出任何未定义的行为,否则无法执行不可达代码。不可达代码不会影响程序输出。不可达代码的存在可能表明程序逻辑中存在错误。编译器不删除的不可达代码会浪费资源,例如:

  • 它会占用目标计算机内存中的空间。

  • 它的存在可导致编译器在围绕不可达代码转移控制时选择更长、更慢的跳转指令。

  • 在一个循环中,它可防止整个循环位于指令缓存中。

Polyspace 实现

如果代码中的语句不可达,Polyspace® 会报告违反了此规则。

检查项会将以下模式标记为不可达代码:

  • 跟在 return、break 或无条件 goto 语句之后的语句

  • 已在同一个翻译单元中定义但从未调用的 static 函数

  • 位于始终为 false 的分支内的代码,例如 if(0)

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示。

示例

全部展开

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 */
}

在此示例中,由于 return 语句之后存在不可达操作,因此会违反规则。

在此示例中,函数包含一个控制表达式计算结果始终为零的分支。


int process_value(int input) {
    int result = input * 2;

    if (0) {                  // Noncompliant - controlling expression is always false
        result = input + 1;
    }

    return result;
}

因为 if(0) 分支内的代码不可达,Polyspace 会报告违反了此规则。控制表达式是一个编译时常量,其计算结果为零,因此该分支内的语句永远无法执行。

检查信息

组:未使用的代码
类别:必需
AGC 类别:必需
PQL 名称:std.misra_c_2012.R2_1

版本历史记录

在 R2014b 中推出

全部展开


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C:2025

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.