switch 语句中缺少枚举情况¶
ID: cpp/missing-case-in-switch
Kind: problem
Security severity:
Severity: warning
Precision: medium
Tags:
- reliability
- correctness
- external/cwe/cwe-478
Query suites:
- cpp-security-and-quality.qls
此规则查找在枚举类型的值上进行切换,但未为所有枚举常量提供 case 或 default case 的 switch
语句。这表明 switch
语句可能无法处理某些情况。
建议¶
为每个枚举常量提供一个 case,或者如果多个常量应该以相同的方式处理,则引入一个 default
case。
示例¶
typedef enum {
RED,
ORANGE,
YELLOW,
GREEN,
BLUE,
INDIGO,
VIOLET
} colors;
int f(colors c) {
switch (c) {
case RED:
//...
case GREEN:
//...
case BLUE:
//...
//wrong: does not use all enum values, and has no default
}
switch(c) {
case RED:
//...
case GREEN:
//...
default:
//correct: does not use all enum values, but has a default
}
}
参考资料¶
Tutorialspoint - C++ 编程语言:C++ switch 语句
MSDN 库:switch 语句 (C++)
M. Henricson 和 E. Nyquist,《工业级 C++》,第 4 章:控制流,Rec 4.5。Prentice Hall PTR,1997(在线可用)。
通用弱点枚举:CWE-478.