Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for empty for loops in C++

Is it possible to check for empty for loops in C++, perhaps some clever template/macro trick? Seems like GCC does not support -Wempty-body for for loops.

like image 366
navigator Avatar asked Feb 08 '23 02:02

navigator


2 Answers

Look into static code analysis tools and their options. CPPCheck is bundled with the IDE I use, performing static analysis before commits.

like image 89
learnvst Avatar answered Feb 09 '23 16:02

learnvst


What do you consider to be an empty for loop? This?

for(;;) {}

This?

for(;;);

How about this?

for(int i = 0; i < 10; ++i);

All of these forms are legal (; is considered an empty statement). The first two are equivalent to while(true) whereas the last one defines i and increments it 10 times. Historically, GCC doesn't optimize this away because for(;;); is a common pattern in kernels and other embedded programs at the end of main().

However...

The following test case does produce warnings (indentation important):

int main()
{
    for (; 1<2; );
    {
      if (1==1);
    }
    while (1==1);
      return 0;
}

main.cpp: In function 'int main()':

main.cpp:4:9: warning: this 'for' clause does not guard... [-Wmisleading-indentation]

         for (; 1<2; );
         ^~~

main.cpp:5:11: note: ...this statement, but the latter is misleadingly indented as if it is guarded by the 'for'

           if (1==1);
           ^~

main.cpp:5:20: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]

           if (1==1);
                    ^

main.cpp:6:9: warning: this 'while' clause does not guard... [-Wmisleading-indentation]

         while (1==1);
         ^~~~~

main.cpp:7:11: note: ...this statement, but the latter is misleadingly indented as if it is guarded by the 'while'

           return 0;
           ^~~~~~

Which means you should be fine if you're worried about a stray semi-colon and your code is properly indented.

like image 25
uh oh somebody needs a pupper Avatar answered Feb 09 '23 14:02

uh oh somebody needs a pupper