Warning bypass: "Control variable does not change inside the loop"

I have a very simple function that created a time delay:

void delay(int time_in_ms) { int t = get_time() + time_in_ms; while (get_time() < t) { }; } delay(750); 

I get a warning that the control variable t does not change inside the while loop. I don’t need to change the variable, I just need to be inside the while loop while the condition is fulfilled. How to get around this in a β€œgood” way?

A warning is generated by the MISRA static analysis tool. Full message:

"The control variable in this loop construct never changes."
MISRA C: 2012 rules applicable to message 2467:

+5
source share
3 answers

Although you may have some knowledge of getTime() , the static analyzer basically assumes that the return value of getTime() never cause an end-of-loop condition, so the loop will potentially be infinite.

So, you need an infinite loop, accepted by the analyzer, in combination with the condition for interruption inside the loop body. As far as I can tell from a quick search, MISRA only accepts for(;;) as an infinite loop.

 for ( ; ; ) { if (t <= get_time()) break; } 

This should not be a warning.

0
source

The static analysis tool seems to expect a normal case, for example:

 int i = 0; while(i < get_size(var)) { do_something(var[i]); i++; } 

However, in your case, the loop control variable is the result of getTime() , and t is the limit.

You can use the real loop control variable. The compiler is probably optimizing it.

 void delay(int time_in_ms) { int t = get_time() + time_in_ms; int current_time; do { current_time = getTime(); } while(current_time < t); } 

Or you can try to figure out what makes your static analysis tool think that t is a loop control variable. This might help declaring const int t .

+2
source

Each compiler or code analysis tool or memory leak analyzer has its own logic and, based on the logic, it gives you a warning or error message. Here in this case, your compiler / tool considers t as a control variable, based on which the while loop should be interrupted. Since the compiler / tool did not detect any code inside the loop block to manipulate the variable t , it raised a warning for you because it thought your while loop could be infinite while loop . Either you can ignore it, you are sure that it will never be an infinite loop, or you can change your code differently (see below, but it may not fix this warning) to avoid this warning.

 void delay(int time_in_ms) { int t = get_time() + time_in_ms; while ( t > get_time() ); } delay(750); 

In the above changes, I moved t to the left side so that your tool does not treat t as a control variable and should not cause any warnings.

0
source

Source: https://habr.com/ru/post/1274471/


All Articles