False Positive on rule cpp:S836

Hi everyone, the developer reached out to me saying that SonarQube falsely reported the cpp:S836 rule (The left operand of ‘+’ is a garbage value). I’m providing the information I have and happy to provide more on request if needed. Please correct us if we’re wrong and point where the issue is as per developers and my view the code looks okay and shouldn’t trigger the rule based on the Rule description.

Thanks in advance.

  • What language is this for?

C++

  • Which rule?

cpp:S836

  • Why do you believe it’s a false-positive/false-negative?

I received this explanation from a developer:

The code is perfectly valid, it checks if both optionals have a value before summing them. Whatever the path you take, left side and right side have a value in that if block.

  • SonarQube Server / Community Build - which version?

Data Center Edition v2026.1.4

  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

This is a code snippet with changed variable names and extracted unnecessary lines. We can see that both variables are initialized before their use.

    std::optional<uint32_t>& foo,
...
        std::optional<uint32_t> bar{};
...
        if(foo.has_value() && bar.has_value())
        {
            foo = *foo + *bar;
        }

Hi @oleksandrmiti!

Can your developer supply a simple code sample that’s compileable so I can throw it into a file and attempt to replicate?