CodeQL 文档

有损函数结果转换

ID: cpp/lossy-function-result-cast
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - correctness
Query suites:
   - cpp-security-and-quality.qls

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

此规则查找函数调用,其结果类型为浮点类型,这些类型会隐式转换为整型。当浮点返回值包含小数部分或取值超出整型可表示的范围时,此类代码的行为可能与预期不符。

建议

考虑更改周围表达式以匹配浮点类型。如果需要舍入,请使用标准函数(例如 truncfloorround)显式进行舍入。

示例

double getWidth();

void f() {
	int width = getWidth();
	
	// ...
}

在此示例中,对 getWidth() 的调用的结果会隐式转换为 int,导致意外丢失精度。要解决此问题,可以将变量 width 的类型从 int 更改为 double

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私