简体   繁体   English

将幻数分配给命名结构成员有什么问题?

[英]What is the problem with assigning magic numbers to named structure members?

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":但是,现在clang-tidy对使用“幻数”感到不满:

warning: 1.1e5 is a magic number;警告:1.1e5 是一个幻数; consider replacing it with a named constant [readability-magic-numbers]考虑用命名常量 [readability-magic-numbers] 替换它

I know I can silence unwanted warnings with // NOLINT comments, but I would like to understand the reasoning behind the warnings.我知道我可以使用// NOLINT注释来消除不需要的警告,但我想了解警告背后的原因。 Is there a situation where the code from the second sample could lead to an error, while the first sample would have been safe?是否存在第二个样本的代码可能导致错误而第一个样本是安全的情况?

Static analysers can't understand what is said in comments, and so they might frown on any use of "magic numbers". Static 分析者无法理解评论中的内容,因此他们可能不赞成使用“幻数”。 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,
};

A constant value is denoted a "magic number" when the static analyzer thinks it comes out of nowhere.当 static 分析器认为它无处不在时,常量值表示为“幻数”。

To fix this issue you can either use a define or a const variable which will hold these values like:要解决此问题,您可以使用 define 或 const 变量来保存这些值,例如:

#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.或者更改分析规则以忽略此类警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM