メインコンテンツ

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

MISRA C++:2008 Rule 5-0-13

The condition of an if-statement and the condition of an iteration-statement shall have type bool.

説明

ルール定義

The condition of an if-statement and the condition of an iteration-statement shall have type bool. 1

根拠

非論理式を ifwhile、および for ステートメントの条件として使用すると、式は暗黙的に bool に変換されます。このような暗黙的な変換は開発者の意図を不明瞭にしたり、エラーを覆い隠したりして、診断するのが難しいバグにつながる可能性があります。次に例を示します。

int flag;
//...
if(flag = 0){
//..
}
上記のコードでは、条件 flag = 0 が代入として意図されているのかどうかが明確ではありません。コンパイラは代入演算の戻り値を、if ステートメントの条件として使用する bool にキャストします。開発者の意図が flag0 が等しいかどうかをテストすることである場合、コードでの = の欠落が、診断するのが難しいバグにつながります。

例外として、type-specifier-seq declarator 形式の条件は boolean 型である必要はありません。次に例を示します。

while(int* p_int = foo())
この場合は型指定子が存在するため、開発者の意図が明らかです。このような代入を使用しないと、可読性の低いコードになる可能性があります。

Polyspace 実装

Polyspace® は、iffor、および while ステートメントでの条件としての非論理式の使用にフラグを設定します。例外として、式が宣言である場合、Polyspace は非 boolean 条件にフラグを設定しません。

トラブルシューティング

ルール違反が想定されるものの、Polyspace から報告されない場合は、コーディング規約違反が想定どおりに表示されない理由の診断を参照してください。

すべて展開する

typedef unsigned char         uint8_t;
typedef signed   int          int32_t;
typedef          bool         bool_t;

#include <cstddef>

namespace NS
{
extern int32_t* fn();
extern bool      fn2();
void foo(uint8_t u8)
{
    while (int32_t* p = fn()) {                   // Compliant by exception
        // Code
    }
    // Avoiding assignment altogather in condition statements
    // sometimes lead to clunky code
    do {
        int32_t* p = fn();
        if (NULL == p) {
            break;
        }
        // Code/*...*/
    } while (true);

    while (bool flag = fn2()) {                      // Compliant
        // Code
    }

    if (u8) {}                                       // Non-compliant

}
};

この例では、Polyspace が条件としての非論理式の使用にフラグを設定します。

do-while ループに示されているように、条件ステートメントで宣言を使用しないと、可読性の低いコードになる可能性があります。例外として、非 boolean 条件が宣言である場合は、このルールに準拠しています。

チェック情報

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

バージョン履歴

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.