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.
Look into static code analysis tools and their options. CPPCheck is bundled with the IDE I use, performing static analysis before commits.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With