メインコンテンツ

MISRA C++:2008 Rule 6-4-1

An if ( condition ) construct shall be followed by a compound statement.The else keyword shall be followed by either a compound statement, or another if statement

説明

ルール定義

An if ( condition ) construct shall be followed by a compound statement.The else keyword shall be followed by either a compound statement, or another if statement. 1

根拠

単一のステートメントを if 文または if...else 文の本体として使用し、その本体を複合ステートメントに変更しようとすると、ロジック エラーが発生して想定外の結果になる可能性があります。このルールにより、単一ステートメントの本体を複合ステートメントの本体に変更しようとする際に、中かっこを省略したり忘れたりすることがなくなります。複合ステートメントを使用できないと、想定外の結果になり、開発者の混乱を招く可能性があります。中かっこ { } を使用して複合ステートメントを作成してください。if ステートメントが単純なもので、単一のステートメントしか含まれていない場合でも、中かっこを使用してください。

Polyspace 実装

if ステートメント、else-if ステートメント、または else ステートメントの後に複合ステートメントが続いていない場合、Polyspace® はこのルールに対する違反を報告します。

トラブルシューティング

ルール違反が想定されるものの、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 は非準拠としてこれにフラグを設定します。

チェック情報

グループ: Statements
カテゴリ: 必要

バージョン履歴

R2013b で導入


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.