False-positive s1854

  • Operating system: windows
  • IDE name and flavor/env: visual studio 2022

Description:

I encountered this false positive on a preincrement of a local variable. Since the variable is preincremented and afterwards used as an indexer, I think the warning is a FP.

Code example

var buffer = new byte[256 * 256 * 3];

  for (var y = 0; y < 256; ++y) 
  {
      for (var x = 0; x < 256; ++x)
      {
          var offset = (y * 256 + x)*3;
          buffer[offset] = 6;
          buffer[++offset] = 9;
          buffer[++offset] = 6;  //here S1854 is raised, unused assignment to local variable offset
      }
  }

Hi @pvld,

This is not a False Positive. You’re assigning +1 value to offset and you never use the new value of offset variable. Thus it is an unused assignment.

Hi Pavel,

I can’t agree on this, the offset is incremented and afterwards used as an indexer to access the array.

I would agree with you if the last statement was
buffer[offset++] = 6;

Best regards

The offset isn’t used after the buffer[++offset] = 6; statement. The code doesn’t read it. For example, this would use the new value and doesn’t raise the issue:

arr[++offset] = offset;

This can be also understood as that you don’t need to modify the offset value to achieve this operation. Because offset isn’t used for anything else after this.

So you mean I should write it as this:

buffer[offset+1] = 6;

Which is basicly the same, but I prefer the ++ notation, since it translates to a single instruction (not that it matters in .NET).

Yes, that’s what S1854 asks.

The code wasn’t too nice before, and will not be much nicer after that. You can consider using post-increment to keep a similar style, where one of them is different than the rest

          var offset = (y * 256 + x)*3;
          buffer[offset++] = 6;
          buffer[offset++] = 9;
          buffer[offset] = 6; 

or unify it like this, to make it regular

          var offset = (y * 256 + x)*3;
          buffer[offset + 0] = 6;
          buffer[offset + 1] = 9;
          buffer[offset + 2] = 6; 
1 Like