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.
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.
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.