« Search  |  Retro Site View (Experimental)  |  Switch to Reader Mode Images: 56K  |  Retro Mode: ON  |  Original Site »
codeql.github.com   (codeql.github.com · converted in 513 ms)
Sections: CodeQL documentation  |  CodeQL overview  |  Writing CodeQL queries  |  CodeQL language guides  |  QL language reference  |  CodeQL standard-libraries  |  CodeQL query help  |  CodeQL repository  |  QL publications  |  Accidental rethrow  |  Array argument size mismatch  |  Bad check for oddness  |  Badly bounded write  |  Call to alloca in a loop  |  Cast from char* to wchar_t*  |  Catching by value

Avoid floats in for loops -- CodeQL query help documentation CodeQL docs

Avoid floats in for loops


ID: cpp/loop-variable-float
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - quality
   - correctness
   - reliability
   - external/jsf
Query suites:
   - cpp-code-quality.qls
   - 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


  • AV Rule 197, Joint Strike Fighter Air Vehicle C++ Coding Standards . Lockheed Martin Corporation, 2005.

  • MISRA C++ Rule 6-5-1, Guidelines for the use of the C++ language in critical systems . The Motor Industry Software Reliability Associate, 2008.

  • FLP30-C. Do not use floating-point variables as loop counters