メインコンテンツ

MISRA C++:2008 Rule 7-1-1

A variable which is not modified shall be const qualified

説明

ルール定義

A variable which is not modified shall be const qualified. 1

根拠

変数 const を宣言すると、変数を誤って変更する可能性を低減できます。

Polyspace 実装

チェッカーは以下にフラグを設定します。

  • const 修飾子は付いていないが、関数本体で変更されない関数パラメーターまたはローカル変数。

  • const 修飾子は付いていないが、存続期間を通じて同じ場所を指すポインター。

整数型、浮動小数点型、enum 型、および boolean 型の関数パラメーターにはフラグは設定されません。

参照またはポインターによって変数が別の関数に渡される場合、チェッカーでは、その変数は変更される可能性があると想定します。そのような変数にはフラグは設定されません。

トラブルシューティング

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

すべて展開する

#include <cstddef>

char getNthChar(const char* str, int N){//Noncompliant
	int index=0;
	while(*(str+index)!='\0'){
		if(index==N)
			return *(str+N);
		++index;
	}
	return '\0';
}
char getNthChar_const_safe(const char* const str, int N){
	int index=0;

	while(*(str+index)!='\0'){
		if(index==N)
		    return *(str+N);
		++index;
	}
	return '\0';
}

関数 getNthChar() では、C 文字列 strconst char* パラメーターとして渡されます。これは、文字列 *strconst であることを意味します。ポインター str は値を変更しないため、関数 getNthChar_const_safe に示すように、ポインター自体に const 修飾子を付ける必要があります。Polyspace は、str パラメーターにフラグを設定します。

チェック情報

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

バージョン履歴

R2018a で導入

すべて展開する


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.