Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bypass the warning: "Control variable is not modified inside the loop"

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

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

delay(750);

I'm getting the warning that the control variable t is not modified inside the while loop. I don't need to modify the variable, I just need to be inside the while loop as long as the condition is met. How to bypass this in a "nice" way?

The warning is created by MISRA static analysis tool. The full message:

"The control variable in this loop construct is never modified"
MISRA C:2012 Rules applicable to message 2467:

like image 709
JohnDoe Avatar asked Oct 29 '22 21:10

JohnDoe


1 Answers

The static analysis tool seems to be expecting a common case like:

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() while t is a limit.

You can use a real loop control variable. The compiler will probably optimize it out.

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 discover what makes your static analysis tool think that t is the loop control variable. A const int t declaration could help.

like image 136
Melebius Avatar answered Nov 12 '22 19:11

Melebius