No issue triggered on anonymous union

Hi,

i came across some code with anonymous unions. I would like to forbid it.

Example code:

bool doIt()
{
   union
   {
      int a;
      bool b;
   } u;
   u.b = false;
   return u.b;
}

I think this rule should have triggered: Rename this union to match the regular expression: [A-Z][a-zA-Z0-9]* sonarlint(cpp:S1878)
The regex does not match, therefor it should fire. It does not. I think the rule description should explicitly mention that anonymous names are also ok.

Is there a different rule for checking this?

PS: The same is true for anonymous structs

Hi,

Since you’re expecting this to fire in SonarLint, could you provide your flavor & version, please?

 
Thx,
Ann

VSCode, extension version v4.3.0.

1 Like

Hi @KUGA2 ,

Thanks for raising this point. I created a ticket to track this discrepancy between the documentation and the actual behavior.

Hi @KUGA2

Could you explain why you consider unions with no name to be problematic? The fact that they have no name means only a few variables of that type will be constructed, and narrowing the scope of usage of something is usually considered desirable.

By the way, do you know that your example does not define an anonymous union, according to the standard, just a union with no name? An anonymous union is a very special beast that would be declared and used that way:

bool doIt()
{
   union // Anonymous union
   {
      int a;
      bool b;
   }; // No variable name either
   b = false; // Union member names are injected in the enclosing scope
   return b;
}

They do have their uses, for instance, see pattern 2 in S6147.

I did not know. I have two issues:

  • I could not find clear documentation whether they (anonymous/unnamed struct/union) are or are not 100% standard or compiler extension
  • abi checker reports minor issues because of the autogenerated names

But leave this discussion out: I think rule cpp:S1878 (and struct cousin) should clearly state that it allows/matches no name.

1 Like

Hello again,

For your first issue, unions/classes with no name are 100% standard. There is no issue about them.
For your second, this is not something that I considered before… Thank you for sharing it with us, we’ll think about it.

And I totally agree that we should improve the documentation of these rules.

2 Likes