NiegodziwyBeru
NiegodziwyBeru

Reputation: 864

Detecting semicolon after loop/if brackets

Is there any flag in GCC (like -Wempty-body in clang), that could help me detect semicolons after the braces of while/for loops? Sometimes it is very hard for humans to find these simple mistakes.

int i = 0;
for (i = 0; i < 10; ++i);
{
    cout << i << endl;
}

I use GCC 4.7.3 and clang 3.2-1~exp9ubuntu1.

Edited: I also check if compilers could help me find these mistakes after "if-else statements".

if (i == 0)
{
    cout << i << endl;
}
else;
{
    cout << i << endl;
}

What is interesting gcc is more helpful than clang (with this flags (-Wall -pedantic -Wempty-body) by printing warning:

main.cpp:30:9: warning: suggest braces around empty body in an ‘else’ statement [-Wempty-body]

Upvotes: 6

Views: 1144

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129344

The obvious answer here is "compile your code with clang++" (although my 2.9 version for x86-64 doesn't seem to catch this particular problem, just like gcc 4.6.3 doesn't catch it - so I'm not entirely convinced the original premise of the question is valid).

This particular code can avoid this problem by using the form, by giving an error for using i after the for-loop itself:

for(int i = ...) 

instead of

int i;
for(i = ...)

Of course, that doesn't work in the case where you want i to have a value after the loop.

[And yes, it's a very annoying error - I've spent several hours staring at the screen to find this sort of bug at times - other times you spot it immediately!]

Upvotes: 1

Abhas Tandon
Abhas Tandon

Reputation: 1889

try

$gcc -Wempty-body foo.c

or

gcc -Wextra -c foo.c

Upvotes: 2

Related Questions