V3159. Modified value of the operand is not used after the increment/decrement operation.

The analyzer has detected a situation where a value is not used after a postfix or prefix increment / decrement operation. Either this operation is redundant or the postfix version should be replaced with the prefix one.

Consider the following example:

int CalculateSomething()
{
  int value = GetSomething();
  ....
  return value++;
}

The incremented value of the local variable 'value' is returned by the 'CalculateSomething' method. However, the postfix operation will actually create a copy of 'value', increment the original variable, and return the copy. In other words, the '++' operator does not affect the value returned by the method in any way. Here is one possible fix to this defect:

int CalculateSomething()
{
  int value = GetSomething();
  ....
  return ++value;
}

The following alternative is even better in signaling that the method must return an incremented value:

int CalculateSomething()
{
  int value = GetSomething();
  ....
  return value + 1;
}

We recommend using the second version as a clearer one.

Consider another synthetic example:

void Foo()
{
  int value = GetSomething();
  Do(value++);
  Do(value++);
  Do(value++);
}

Each time the 'Do' function is called, its argument is incremented. The last increment has no practical use since the incremented value is not used after that. However, it cannot be viewed as a defect since it is written simply for the sake of neater appearance. The analyzer will recognize this intention and ignore this spot. No warning is issued when the variable is incremented more than twice in succession.

Still, we recommend using the following pattern:

void Foo()
{
  int value = GetSomething();
  Do(value++);
  Do(value++);
  Do(value);
}

As an alternative solution, you can write as follows:

void Foo()
{
  int value = GetSomething();
  Do(value + 0);
  Do(value + 1);
  Do(value + 2);
}

This diagnostic is classified as:


Bugs Found

Checked Projects
412
Collected Errors
14 132
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →
Accept