主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C++:2008 Rule 0-1-6

A project shall not contain instances of non-volatile variables being given values that are never subsequently used.

自 R2023a 起

描述

规则定义

A project shall not contain instances of non-volatile variables being given values that are never subsequently used. 1

理由

如果您为某个变量赋了值,但后面并不会用到该变量值,则该赋值可能会导致编程错误。您可能本打算使用该变量但没有使用,或者您可能错误地使用了其他变量。

Polyspace 实现

向作用域为文件的局部静态变量赋值后,如果所赋值没有被使用过,则此规则检查项会报告赋值违规。(此检查项会将没有 extern 设定符且符合 const 条件的全局变量视为作用域为文件的静态变量。)

此检查项会报告以下方面的违规:

  • 初始化(如果未使用已初始化的变量)。

  • 赋值(如果未使用所赋值)。

    例如,您为某个变量赋了一个值,但在下次读取该变量之前,又赋了另一个值。在这种情况下,此检查项会标记第一个冗余赋值。唯一例外的情况是在变量初始化时赋值,然后值被覆盖。

如果先前迭代中的赋值不是冗余的,此检查项不会报告在循环的最后一次迭代中的赋值违规。例如,函数 func() 中循环的最后一次迭代中的赋值 prevIter = i 冗余,但先前迭代中的赋值不是冗余的。

void doSomething(int);

void func() {
  int prevIter=-1, uBound=100;
  for(int i=0; i < uBound; i++) {
        doSomething(prevIter);
        prevIter = i;
  }
}

故障排除

如果您预计存在违规,而 Polyspace® 未报告该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

class largeInteger {
       largeInteger(int d1, int d2, int d3):
            lastFiveDigits(d1), nextFiveDigits(d2), firstFiveDigits(d3){}
       largeInteger& operator=(const largeInteger& other) {
            if(&other !=this) {
              firstFiveDigits = other.firstFiveDigits;
              nextFiveDigits = other.nextFiveDigits;
              lastFiveDigits = other.lastFiveDigits;
            }
            return *this;
       }
       void printIntegerValue();
    private:
        int firstFiveDigits;
        int nextFiveDigits;
        int lastFiveDigits;
};

bool compareValues(largeInteger, largeInteger);

void func() {
    largeInteger largeUnit{10000,0,0}; //Compliant
    largeInteger smallUnit{1,0,0}; //Compliant
    largeInteger tinyUnit{0,1,0}; //Noncompliant
    if(compareValues (largeUnit, smallUnit)) {
        //Perform some action   
    }
}

在此示例中,对变量 tinyUnit 进行了初始化但从未被用到。

检查信息

组:与语言无关的问题
类别:必需

版本历史记录

在 R2023a 中推出

全部展开


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.