C++ S6004 triggers on static variables

The rule cpp:S6004 “Use the init-statement to declare “useAircraftAsRotations” inside the if statement.” triggers on variables that would otherwise fit the pattern, but are static. Static variables can not be declared in the init statement.

This is on SonarQube Server 2025.1.

Shows up in code like:

void A::do() {
  static const bool useFeature = getFeatureFlag();
  if (useFeature) {
    doNewThing();
  }
  doThing();
}

Thanks for your report!

I had a quick look at the C++ Standard for the if statement . After following the simple-declaration link a few steps it allows a storage-class-specifier, which would allow static.

I’ve tested with Godbolt and all mainstream compilers accept the static. (Note that dois a keyword, so I renamed the function.)

Can you explain why you believe static variables can’t be declared in the init-statement?

Hi Mark!

Turns out it’s valid to do:

if (static bool a = true; a) {

but not:

if (static bool a = true) {

I tried to do the latter and it fail. I was mistaken.

Erik

Hi Erik,

Thanks for your update!