cpp:S864 on simple addition / substraction

size_t calculate(size_t t1, size_t t2)
   return t1 + t2 - 1;

I think SQ/SL should not report this issue. It is annoying and adding braces just makes the code less readable. There is no confusion about this code. It would be the same result no matter the operator precedence or if you add braces anywhere. One could argue, adding braces would be an brain overload because the reader might think about why the author added them here.

Do not get me wrong. There are cases where braces and therefore this rule are useful. Even with a simple change, braces are useful. If you turn the arguments t1 - 1 + t2, braces would be helpful to show the authors intentions. However, in my original example, it is just annoying.

  • What language is this for?
  • Are you using
    • SonarLint - which IDE/version?
      VSCode 1.86.2, Extension v4.3.0
      • in connected mode with SonarQube or SonarCloud?
        connected to SQ

Hey @KUGA2

I don’t quite understand your point here.

Why are braces here more helpful than in your screenshot example (t1 + t2 - 1)

In the changed version t1 - 1 + t2 the operator precedence is important. The result would be different if 1 + t2 would be evaluated first. So it is correct to demand braces for making operator precedence explicit.

In the original version it does not mater which operation is evaluated is first. The result is always the same (because size_t can correctly overflow). Therefore the rule should not trigger!

Hello @KUGA2.

Thanks for your feedback. We discussed this topic with the team and concluded that this is the desired behavior.

On the one hand, you are correct that the behavior with size_t correctly warps around, and the parenthesis does not influence the result in your particular example.

However, this particular case requires quite an advanced understanding of the language and the possible subtle nuances of an expression. For example, if an implicit conversion was at play, the result could be different. It also means that the writer and all the future readers of this code will have to figure out if it does what was intended. In your small example, this may be okay-ish. Still, in larger examples/functions, you would no longer be able to locally reason about your code – you would at least need to know the exact type, which can potentially be aliases or template parameters, to know if the expression is correct.

In other words, scenarios that behave identically regardless of parentheses are limited. Not having parentheses can result in confusion or brain overload – I think this is where we mostly disagree with you.

Additionally, it is often preferable to be consistent in a code base. From this point of view, it is better to always add the parenthesis regardless of the signedness of the types, their sizes, and whether they are templates.