主要内容

MISRA C++:2023 Rule 9.4.1

All if ... else if constructs shall be terminated with an else statement

自 R2024b 起

描述

All if ... else if constructs shall be terminated with an else statement. 1

理由

else 语句结束 if... else if 语句是一种防御性编程。这个最终的 else 语句起到故障安全机制的作用,以防出现代码执行越过 ifelse if 语句的特殊情况。

当一个 if 语句后面跟着一个或多个 else if 语句时,在最后一个 else if 语句后添加一个 else 语句。在 else 语句内提供一个操作。如果无需执行任何操作,提供一条注释,说明不执行操作的原因。

Polyspace 实现

只要 if … else if 构造没有以 else 语句结尾,Polyspace® 就会报告此缺陷。

故障排除

如果您预期会出现违规,而 Polyspace 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

#include <cstdint>

int example(int test, int result)
{
    if (test > 5) 
    {
        test--;
        result = test + result;  
    } 
    else if (test <= 5) 			//Noncompliant		
    {
        result = test - result;   
    } 

    return result;
}

因为最后一个 else if 语句后面没有结束 else 语句,所以 Polyspace 将其标记为不合规。即使应该不会出现 test 的值同时越过 ifelse if 语句的情况,但仍需要添加额外的 else 语句。

检查信息

组:声明
类别:必需
PQL 名称:std.misra_cpp_2023.R9_4_1

版本历史记录

在 R2024b 中推出


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.