主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C:2012 Rule 2.1

A project shall not contain unreachable code

描述

规则定义

A project shall not contain unreachable code 1 .

理由

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

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

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

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

Polyspace 实现

如果无法访问代码中的语句,Polyspace® 会报告缺陷。

故障排除

如果您预计存在违规,但未看到该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

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 语句之后存在不可达操作,因此会违反规则。

检查信息

组:未使用的代码
类别:必需
AGC 类别:必需

版本历史记录

在 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++:2008

  • MISRA C++:2023

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