C++ / S109: Magic number in initialization list

Hello,

Let the class:

class MyClass
{
    MyClass();
    ~MyClass() = default;
    int32_t m_integer;
    float_t m_float{ 5.0f };   // Won't raise S105
};

MyClass::MyClass() :
    m_data{5}   // Will raise S105
{}

Please explain me why the value for the m_integer’s initialization is more magical than the m_float’s one ?

1 Like

Hi @Oodini ,

Indeed, that rule only triggers for integers and not for floating point constants. I couldn’t find any history of it being a conscious decision, so I created a ticket to change that.

Thanks for raising it.

The point is not between integers and floats, but between initialization with declaration, and initialization with initialization list.

There are two subjects indeed:

  • we don’t raise on floating point numbers no matter what, so 5.0f will never raise no matter how it is used. I don’t see a good reason for that one.
  • we don’t raise on variable declaration but raise on constructor initializers. That second one is quite philosophical and can definitely be wrong sometime. A member declaration with initialization directly gives a single name to a single value, which we expect to be clear enough to not be “magical”. When you choose to use a constructor initializer instead of initializing the member variable in its declaration, it is potentially because multiple constructors give different values to that member, so a single name for multiple values.

We provide S109, but the reason it is not part of the default quality profile is that it is not a rule we are confident in. It tries to guess with a simple heuristic how clear the code is, but that comes with false positives and false negatives.