CodeQL 文档

在建议使用枚举的情况下使用整数

ID: cpp/integer-used-for-enum
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - maintainability
   - readability
   - language-features
   - external/jsf
Query suites:
   - cpp-security-and-quality.qls

点击查看 CodeQL 存储库中的查询

此规则查找使用整数而不是枚举的 switch 语句。在处理有限数量的选择时,建议使用枚举,因为它们可以更轻松地查看是否遗漏了某个情况。

建议

使用枚举而不是整数来表示一组有限的选择。

示例

typedef enum {
	CASE_VAL1,
	CASE_VAL2
} caseVals;

void f() {
	int caseVal;
	//Wrong: switch statement uses an integer
	switch(caseVal) {
	case 1:
		//...
	case 0xFF:
		//...
	default:
		//...
	}

	//Correct: switch statement uses enum. It is easier to see if a case 
	//has been left out, and that all cases are valid values
	caseVals caseVal2;
	switch (caseVal2) {
	case CASE_VAL1:
		//...
	case CASE_VAL2:
		//...
	default:
	}
}

参考

  • AV 规则 148,联合攻击战斗机飞行器 C++ 编码标准。洛克希德·马丁公司,2005 年。

  • C++ Switch 语句

  • ©GitHub 公司
  • 条款
  • 隐私