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?
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:
Or like:
And then use it into your structure:
Or change the analysis rules to ignore this type of warning.