主要内容

MISRA C++:2023 Rule 9.3.1

The body of an iteration-statement or a selection-statement shall be a compound-statement

自 R2024b 起

描述

The body of an iteration-statement or a selection-statement shall be a compound-statement. 1

理由

当在子表达式中使用时,赋值运算符会产生难以预测的副作用。这些副作用可能会产生与开发人员预期相反的结果。此规则有助于避免将赋值运算符 (=) 与等于运算符 (==) 混淆。不要使用赋值运算符的结果。

Polyspace 实现

如果满足以下任一条件,则 Polyspace® 会报告违反了此规则:

  • if 语句、else-if 语句或 else 语句后面未跟复合语句。

  • forswitchwhile do-while 语句后面未紧跟左花括号。例如

    for (i=init_val; i > 0; i--)
       if (arr[i] < 0)
          arr[i] = 0;

故障排除

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

示例

全部展开

#include <cstdint>

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

    return result;
}

因为 else 语句没有使用 { } 花括号来构成复合语句,所以 Polyspace 将其标记为不合规。

检查信息

组:声明
类别:必需
PQL 名称:std.misra_cpp_2023.R9_3_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.