Home > other >  What is the problem with assigning magic numbers to named structure members?
What is the problem with assigning magic numbers to named structure members?

Time:12-09

Consider the following code:

const double Motor_Kv = 1.1e5; // Motor constant, [rpm/V]
const double Motor_R = 2e-2;   // Winding resistance, [Ohm]
const double Motor_J = 3e-6;   // Rotor angular mass, [kg*m2]

This has been refactored to use a structure:

const MotorParams Motor = {
    .Kv = 1.1e5, // Motor constant, [rpm/V]
    .R = 2e-2,   // Winding resistance, [Ohm]
    .J = 3e-6,   // Rotor angular mass, [kg*m2]
};

However, now clang-tidy is unhappy about the use of "magic numbers":

warning: 1.1e5 is a magic number; consider replacing it with a named constant [readability-magic-numbers]

I know I can silence unwanted warnings with // NOLINT comments, but I would like to understand the reasoning behind the warnings. Is there a situation where the code from the second sample could lead to an error, while the first sample would have been safe?

CodePudding user response:

Static analysers can't understand what is said in comments, and so they might frown on any use of "magic numbers". You can prevent this by doing something along the lines of:

#define MOTOR_RPM_V         1.1e5  // Motor constant, [rpm/V]
#define MOTOR_WINDRES_OHM    2e-2  // Winding resistance, [Ohm]
#define MOTOR_ANGMASS_KG     3e-6  // Rotor angular mass, [kg*m2]

const MotorParams Motor = {
    .Kv = MOTOR_RPM_V,
    .R  = MOTOR_WINDRES_OHM,
    .J  = MOTOR_ANGMASS_KG,
};

CodePudding user response:

A constant value is denoted a "magic number" when the static analyzer thinks it comes out of nowhere.

To fix this issue you can either use a define or a const variable which will hold these values like:

#define MOTOR_SPEC_KV 1.1e5

Or like:

static const double MOTOR_SPEC_KV = 1.1e5;

And then use it into your structure:

const struct MotorParam params = {
    .Kv = MOTOR_SPEC_KV,
    ....
};

Or change the analysis rules to ignore this type of warning.

  • Related