← 返回首页
Avoid floats in for loops — CodeQL query help documentation CodeQL docs
CodeQL documentation
CodeQL resources

Avoid floats in for loops

ID: cpp/loop-variable-float Kind: problem Security severity: Severity: recommendation Precision: high Tags: - correctness - reliability - external/jsf Query suites: - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule finds float variables being used as loop counter. float values are prone to rounding and truncation. In particular, very large and very small float values are prone to rounding errors and could lead to unexpected loop behavior.

Recommendation

Use an integral variable instead of a float variable for the loop counter.

Example

void f() { float i = 0.0f; //wrong: float used as loop counter for (i = 0; i < 1000000.0f; i++) { //may execute 1000000 +x/-x times //... } for (i = 0; i < 100000000.0f; i++) { //may never terminate, as rounding errors //cancel out the addition of 1.0 once //i becomes large enough //... } }

References