Lossy function result cast¶
ID: cpp/lossy-function-result-castKind: problemSecurity severity: Severity: warningPrecision: mediumTags: - correctnessQuery suites: - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
This rule finds function calls whose result type is a floating point type, which are implicitly cast to an integral type. Such code may not behave as intended when the floating point return value has a fractional part, or takes an extreme value outside the range that can be represented by the integer type.
Recommendation¶
Consider changing the surrounding expression to match the floating point type. If rounding is intended, explicitly round using a standard function such astrunc,floor orround.
Example¶
doublegetWidth();voidf(){intwidth=getWidth();// ...}
In this example, the result of the call togetWidth() is implicitly cast toint, resulting in an unintended loss of accuracy. To fix this, the type of variablewidth could be changed fromint todouble.
References¶
Microsoft Visual C++ Documentation:Type Conversions and Type Safety (Modern C++).
Cplusplus.com:Type conversions.