3.4 Warning options in -Wall
As described earlier (see section 2.1 Compiling a simple C program), the warning
option -Wall
enables warnings for many common errors, and
should always be used. It combines a large
number of other, more specific, warning options which can also be
selected individually. Here is a summary of these options:
-Wcomment
(included in -Wall
)
-
This option warns about nested comments. Nested comments typically
arise when a section of code containing comments is later commented
out:
/* commented out
double x = 1.23 ; /* x-position */
*/
Nested comments can be a source of confusion--the safe way to "comment
out" a section of code containing comments is to surround it with the
preprocessor directive #if 0 ... #endif
:
/* commented out */
#if 0
double x = 1.23 ; /* x-position */
#endif
-Wformat
(included in -Wall
)
-
This option warns about the incorrect use of format strings in functions
such as
printf
and scanf
, where the format specifier does
not agree with the type of the corresponding function argument.
-Wunused
(included in -Wall
)
-
This option warns about unused variables. When a variable is declared
but not used this can be the result of another variable being
accidentally substituted in its place. If the variable is genuinely not
needed it can be removed from the source code.
-Wimplicit
(included in -Wall
)
-
This option warns about any functions that are used without being
declared. The most common reason for a function to be used without
being declared is forgetting to include a header file.
-Wreturn-type
(included in -Wall
)
-
This option warns about functions that are defined without a return type
but not declared
void
. It also catches empty return
statements in functions that are not declared void
.
For example, the following program does not use an explicit return
value:
#include <stdio.h>
int
main (void)
{
printf ("hello world\n");
return;
}
The lack of a return value in the code above could be the result of an
accidental omission by the programmer--the value returned by the main
function is actually the return value of the printf
function (the
number of characters printed). To avoid ambiguity, it is preferable to
use an explicit value in the return statement, either as a variable or a
constant, such as return 0
.
The complete set of warning options included in -Wall
can be
found in the GCC Reference Manual "Using GCC" (see section Further reading). The options included in -Wall
have the common
characteristic that they report constructions which are always wrong, or
can easily be rewritten in an unambiguously correct way. This is why
they are so useful--any warning produced by -Wall
can be
taken as an indication of a potentially serious problem.