主要内容

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 进行限定但在其生命周期内指向同一位置的指针。

整数、浮点、枚举和布尔类型的函数参数不会被标记出来。

如果一个变量通过引用或指针传递给另一个函数,则检查项会假设该变量可能会被修改。这些变量不会被标记出来。

故障排除

如果您预期会出现违规,而 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 字符串 str 被传递为 const char* 参数,意味着字符串 *strconst。因为指针 str 不更改值,所以必须为该指针本身使用 const 进行限定,如函数 getNthChar_const_safe 中所示。Polyspace 会将参数 str 标记出来。

检查信息

组:声明
类别:必需

版本历史记录

在 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.