☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

同类枚举项的值不应相同

5.2.1 ID_duplicateEnumerator
目录 › next › previous

枚举项用于标记不同的事物,在同一枚举类型中,名称不同但值相同的枚举项往往意味着错误。

示例:

enum Color {
    red = 1,
    yellow = 2,
    blue = 2,    // Non-compliant, same value as ‘yellow’
};

例中三个枚举项应分别表示三种颜色,但 blue 与 yellow 的值相同会造成逻辑错误。

又如:

enum Fruit {
    apple,
    pear,
    grape,
    favorite = grape,  // Non-compliant
};

例中 Fruit 定义了三种水果,而 favorite 表示最喜欢的水果,与其他枚举项不是同一层面的概念,不应聚为一类。

应采用更结构化的方式:

enum Fruit {
    apple, pear, grape
};

Fruit favorite() {
    return grape;
}

参考

C++ Core Guidelines Enum.8 MISRA C 2012 8.12
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.