メインコンテンツ

MISRA C++:2008 Rule 6-5-6

A loop-control-variable other than the loop-counter which is modified in statement shall have type bool.

説明

ルール定義

A loop-control-variable other than the loop-counter which is modified in statement shall have type bool. 1

根拠

ループは、ループ カウンター値が終了条件を満たした時点で終了します。ループを早期に終了する必要がある場合は、追加のループ制御変数を使用できます。

次に例を示します。

for(ctr = 0 ; ctr <= 10; ctr++) {…} は、ctr の値が 10 より大きい場合に終了します。

for(ctr = 0 ; ctr <= 10 && level > 0; ctr++) {…} は、ctr の値が 10 より大きいか、level の値が 0 より大きい場合に終了します。

2 番目のインスタンスでは、条件 level >= 0 がループを早期に終了させる理由が明確ではありません。早期終了のためのループ制御変数として boolean 変数を使用することで、早期終了状態を表す、よりわかりやすい名前を使用できます。

以下に例を示します。

for(ctr = 0 ; ctr <= 10 && fuelTankNotEmpty; ctr++) 
{
    /...
    fuelTankNotEmpty = (level >= 0);
}

この boolean 変数はフラグと呼ばれます。boolean 型フラグのほうが、ループ制御ロジックを理解しやすくなります。

Polyspace 実装

Polyspace® は、非 boolean 型ループ制御変数がループ ステートメント内で変更される場合は常にこの欠陥を報告します。

トラブルシューティング

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

すべて展開する

#include <cstdint>

int32_t ctr, level = 1;
bool fuelTankNotEmpty = true;

void example()
{
	for(ctr = 0 ; ctr <= 10 && level >= 0; ctr++)		//Noncompliant
	{
		level--;
	}
	
	for (ctr = 0; ctr <= 10 && fuelTankNotEmpty; ctr++)	//Compliant
	{
		level--;
		fuelTankNotEmpty = (level >= 0);
	}

}

最初の for ループで、level は boolean 型ではなく、ステートメント内で変更されるため、Polyspace は非準拠としてこれにフラグを設定します。

2 番目のループに、このルールに準拠した boolean 型フラグの使用方法が示されています。

チェック情報

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