Discussion:
Empty statement warning!
Agnar Renolen
2011-11-25 12:25:48 UTC
Permalink
I'm sometimes doing the obvious mistake of adding a ";" after an if-statement.

if (<expression>);
DoSomething();

This error sometimes causes weird behaviour of the program, and are hard to spot in the code.

I once read a recommendation that you should always add curly braces, even if for single statement blocks:

if (<expression>);
{
DoSomething();
}

...as this would normally cause a good compiler to issue a warning.

But, using XCode on Mac (built on top of GCC) I'm not warned for these errors, and I can't find an option in Xcode to enable such a warning.

Is there another way to make gcc issue a warning for empty statements such as the one above (I know it's legal C / C++ code, but it's use is fairly narrow I would say).

Agnar

--
Agnar Renolen
eMap as (www.emap.no)
David Brown
2011-11-25 13:03:28 UTC
Permalink
Post by Agnar Renolen
I'm sometimes doing the obvious mistake of adding a ";" after an if-statement.
if (<expression>); DoSomething();
This error sometimes causes weird behaviour of the program, and are
hard to spot in the code.
I once read a recommendation that you should always add curly braces,
if (<expression>); { DoSomething(); }
...as this would normally cause a good compiler to issue a warning.
That's not why you should use braces. The main reasons are to avoid it
being unclear what is in the scope of the "if", especially if the
statement is on a separate line, and to avoid problems if DoSomething()
happened to be a macro.

Personally, I think it is a strange sort of typo to add a semicolon
after the "if" here, and I wouldn't rate it as a common problem (unlike
mixups with "=" and "==", for example). But maybe you see it more often.
Post by Agnar Renolen
But, using XCode on Mac (built on top of GCC) I'm not warned for
these errors, and I can't find an option in Xcode to enable such a
warning.
Is there another way to make gcc issue a warning for empty statements
such as the one above (I know it's legal C / C++ code, but it's use
is fairly narrow I would say).
I thought XCode used lvm rather than gcc?

Anyway, for gcc you need to have the appropriate warnings enabled. In
this case it's "-Wempty-body", which you get automatically with
"-Wextra". Some gcc warnings are only active when you have enabled at
least some optimisation, but I think this one will always work.

Continue reading on narkive:
Loading...