If your editor is your first weapon in the battle against bugs, then your compiler is your second. All compilers have the ability to scan code and find common errors, but you usually have to enable this error checking by invoking the appropriate option.
Many of the compiler warning options, like GCC's -Wtraditional
switch, are probably overkill except in special situations. However, don't even think about using GCC without using -Wall
each and every time. For example, one of the most common mistakes that new C programmers make is illustrated by the following statement:
if (a = b) printf("Equality for all!\n");
This is valid C code, and GCC will merrily compile it. The variable a
is assigned the value of b
, and that value is used in the conditional. However, this is almost certainly not what the programmer meant to do. Using GCC's -Wall
switches, you'll at least get a warning alerting you that this code might be a mistake:
$ gcc try.c $ gcc -Wall try.c try.c: In function `main': try.c:8: warning: suggest parentheses around assignment used as truth value
GCC suggests that you parenthesize the assignment a = b
before using it as a truth value, in the same way that you do when you assign a value and perform a comparison: if ((fp = fopen("myfile", "w")) == NULL)
. GCC is essentially asking, "Are you sure you want the assignment a = b
here, instead of the test for equality a == b
?"
You should always use your compiler's error-checking options, and if you teach programming, you should require your students to use them, too, in order to instill good habits. GCC users should always use -Wall
, even for the smallest "Hello, world!" program. We've found that it is prudent to use -Wmissing-prototypes
and -Wmissing-declarations
, as well. Indeed, if you have a spare 10 minutes, scanning the GCC man page and reading the compiler warning section is a great way to spend the time, especially if you're going to be programming under Unix to any significant extent.