メインコンテンツ

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

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

説明

ルール定義

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

根拠

if...else if 文を else ステートメントで終えることは、防御的プログラミングです。この最後の else ステートメントは、コードが if および else if ステートメントを偽として通り過ぎるという特異な状況が発生した場合の安全策としての役割を果たします。

if ステートメントの後に 1 つ以上の 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;  
    } 

    return result;
}

この if 文には else if ステートメントが存在しないため、この文に最後の else ステートメントを含める必要はありません。

#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 はこれを非準拠としてマークします。テストの値が if ステートメントと else if ステートメントの両方を偽として通り過ぎる状況は発生しないはずであっても、else ステートメントを追加する必要があります。

チェック情報

グループ: 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.