2.2 Finding errors in a simple program
As mentioned above, compiler warnings are an essential aid when
programming in C and C++. To demonstrate this, the program below
contains a subtle error: it uses the function printf
incorrectly,
by specifying a floating-point format '%f' for an integer value:
#include <stdio.h>
int
main (void)
{
printf ("Two plus two is %f\n", 4);
return 0;
}
This error is not obvious at first sight, but can be detected by the
compiler if the warning option -Wall
has been enabled.
Compiling the program above, 'bad.c', with the warning option
-Wall
produces the following message:
$ gcc -Wall bad.c -o bad
bad.c: In function `main':
bad.c:6: warning: double format, different
type arg (arg 2)
This indicates that a format string has been used incorrectly in the
file 'bad.c' at line 6. The messages produced by GCC always have
the form file:line-number:message. The compiler distinguishes
between error messages, which prevent successful compilation, and
warning messages which indicate possible problems (but do not stop
the program from compiling).
In this case, the correct format specifier should be '%d'
for an integer argument. The allowed format specifiers for
printf
can be found in any general book on C, such as the
GNU C Library Reference Manual (see section Further reading).
Without the warning option -Wall
the program appears to compile
cleanly, but produces incorrect results:
$ gcc bad.c -o bad
$ ./bad
Two plus two is 2.585495 (incorrect output)
The incorrect format specifier causes the output to be corrupted,
because the function printf
is passed an integer instead of a
floating-point number. Integers and floating-point numbers are stored
in different formats in memory, and generally occupy different numbers
of bytes, leading to a spurious result. The actual output shown above
may differ, depending on the specific platform and environment.
Clearly, it is very dangerous to develop a program without checking for
compiler warnings. If there are any functions which are not used
correctly they can cause the program to crash or produce incorrect
results. Turning on the compiler warning option -Wall
will
catch many of the commonest errors which occur in C programming.