Empty statement warning!
David Brown
david@westcontrol.com
Sat Nov 26 06:22:00 GMT 2011
On 25/11/2011 13:25, Agnar Renolen wrote:
> 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.
>
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.
> 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.
More information about the Gcc-help
mailing list