Main Content

MISRA C++:2023 Rule 0.1.1

A value should not be unnecessarily written to a local object

Since R2024b

Description

Rule Definition

A value should not be unnecessarily written to a local object.

Rationale

If you assign a value to a variable but do not use the variable value later, the assignment might indicate a programming error. You may have intended to use the variable but did not, or you may have incorrectly used a different variable instead.

Polyspace Implementation

The rule checker reports violations for value assignments to local and static variables with file scope if the assigned values are not subsequently used. (The checker considers const-qualified global variables without the extern specifier as static variables with file scope.)

The checker reports violations on:

  • Initializations if the initialized variable is not used.

  • Value assignments if the assigned values are not used.

    For instance, you assigned a value to a variable and before the next read of the variable, assigned a different value. In this case, the checker flags the first redundant assignment. The only exception is the case where a value is assigned at variable initialization and later overwritten.

The checker does not report violations on assignments in the last iteration of a loop, if the assignments in the previous iterations are not redundant. For instance, the assignment prevIter = i in the last iteration of the loop in the function func() is redundant but the assignments in the previous iterations are not.

void doSomething(int);

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

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

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   
    }
}

In this example, the variable tinyUnit is initialized but never used.

Check Information

Group: Language Independent Issues
Category: Advisory

Version History

Introduced in R2024b