逗号前的误导性缩进¶
ID: cpp/comma-before-misleading-indentation
Kind: problem
Security severity: 7.8
Severity: warning
Precision: medium
Tags:
- maintainability
- readability
- security
- external/cwe/cwe-1078
- external/cwe/cwe-670
Query suites:
- cpp-security-extended.qls
- cpp-security-and-quality.qls
如果逗号运算符后的表达式所在的列号早于逗号运算符之前的表达式,则这种可疑的缩进可能表明存在逻辑错误,该错误是由可能逃过视觉检查的拼写错误造成的。
警告:由于 CodeQL 目前无法区分空格中的制表符和空格,因此此查询的精度中等。如果文件包含混合制表符和空格,则警报可能会突出显示对于制表符大小的一个值正确缩进但对于其他制表符大小则不正确的代码。
建议¶
为确保您的代码易于阅读和审查,请在逗号运算符周围使用标准缩进。始终在与左侧操作数相同的缩进级别(列号)处开始右侧操作数。这使得其他开发人员更容易了解您的代码的预期行为。
一致地使用空格来传达您的编码意图。尽可能避免在文件中混合制表符和空格。如果需要混合使用,请保持一致性。
示例¶
此示例展示了三种不同的代码编写方式。第一个示例包含逗号而不是分号,这意味着最后一行是 if
语句的一部分,即使缩进暗示它是独立的。第二个示例看起来不同,但功能上与第一个示例相同。开发人员更有可能想编写第三个示例。
/*
* In this example, the developer intended to use a semicolon but accidentally used a comma:
*/
enum privileges entitlements = NONE;
if (is_admin)
entitlements = FULL, // BAD
restrict_privileges(entitlements);
/*
* The use of a comma means that the first example is equivalent to this second example:
*/
enum privileges entitlements = NONE;
if (is_admin) {
entitlements = FULL;
restrict_privileges(entitlements);
}
/*
* The indentation of the first example suggests that the developer probably intended the following code:
*/
enum privileges entitlements = NONE;
if (is_admin)
entitlements = FULL; // GOOD
restrict_privileges(entitlements);
参考资料¶
维基百科:逗号运算符
维基百科:缩进风格 - 制表符、空格和缩进大小
通用弱点枚举:CWE-1078.
通用弱点枚举:CWE-670.