メインコンテンツ

MISRA C:2023 Rule 14.4

The controlling expression of an if statement and the controlling expression of an iteration-statement shall have essentially Boolean type

R2024a 以降

説明

ルール定義

The controlling expression of an if statement and the controlling expression of an iteration-statement shall have essentially Boolean type 1

根拠

厳密な型指定では if ステートメントまたは反復ステートメントの制御式は "実質的な boolean 型" でなければなりません。

Polyspace 実装

Polyspace® は整数の定数、たとえば if(2) にフラグを立てません。

解析では、bool または _Bool の boolean 型 (stdbool.h で定義) が認識されます。

オプション [有効な boolean 型] (-boolean-types) を使用して、実質的な boolean 型を定義することもできます。

トラブルシューティング

ルール違反を想定していてもその違反が表示されない場合、コーディング規約違反が想定どおりに表示されない理由の診断を参照します。

すべて展開する

#include <stdbool.h>
#include <stdlib.h>

#define TRUE 1

typedef _Bool bool_t;
extern bool_t flag;

void foo(void){
    int *p = 1;
    int *q = 0;
    int i = 0;
    while(p){}           /* Non-compliant - p is a pointer */

    while(q != NULL){}   /* Compliant */

    while(TRUE){}        /* Compliant */

    while(flag){}        /* Compliant */

    if(i){}              /* Non-compliant - int32_t is not boolean */

    if(i != 0){}         /* Compliant */

    for(int i=-10; i;i++){}   /* Non-compliant - int32_t is not boolean */

    for(int i=0; i<10;i++){}  /* Compliant */
}

この例では、whileif および for ステートメント内のさまざまな制御式を示しています。

準拠していないステートメント (最初の whileif および for の例)、は単一の非 boolean 変数を使用しています。単一の変数を制御ステートメントとして使用する場合、実質的な boolean 型でなければなりません (17 行目および 19 行目)。論理式も MISRA™ に準拠しています。

チェック情報

グループ: 制御ステートメントの式
カテゴリ: 必要
AGC カテゴリ: 推奨

バージョン履歴

R2024a で導入


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.