Frequently Made C Programming Errors
Misplaced ';' after an if statement
------------------------------------
if( character == 'a' );
puts("This always happens");
The ';' character is a complete statement that does nothing. The
example above will execute the ';' (nothing) based on the test. The
puts() will execute regardless of the test.
Using '=' instead of '=='
-------------------------
if( character = 'a' )
The '=' operator assigns values. The '==' operator tests values.
The above if statement sets the variable to 'a', and always returns
true. The programmer probably meant to test if the variable was
equal to 'a'. This mistake is very common among beginners, and even
occasionally catches experts.
Operator Precedence Errors
--------------------------
if( count= Counter() || alphabet= Soup() )
C evaluates expressions in a strictly defined order. The logical OR
operator "||" has higher priority than the assignment operator "=".
The above statement will OR the return value of Counter() with the
value of alphabet -- certainly not what the programmer intended.
Remember, when in doubt, use parenthesis:
if( (count= Counter()) || (alphabet= Soup()) )
Confusing a character constant with a string
--------------------------------------------
text = 'a';
text = "a";
The first statement sets text equal to the character 'a'. The second
statement sets text equal to a pointer to a string, containing the
character 'a'. For the first case to work, text would nee to be of
type char. For the second case to work, text would need to be type
char *, pointer to char.
Omitting the break; statement in a switch call
----------------------------------------------
switch( c ) {
case 'a':
puts("This is case a");
case 'b':
puts("This is case b");
default:
}
Unless a break; statement is added, 'case a' will execute the code
for both 'case a' and 'case b'.
Forgetting to count the NULL in strings
---------------------------------------
memory = malloc( strlen("hello") );
The most common C errors, both for beginners and experts, are
off-by-one errors. When allocating memory for a C strings, remember
to include an extra character for the NULL terminator. The above
malloc call allocates only five bytes, not the six required.
Using the wrong bounds for an array
-----------------------------------
char array[100];
For this example, legal array index values range from 0 to 99.
array[100] is not within the array. The first member of the array is
array[0], not array[1]. C does no checking of array bounds.
Inserting a ';' after a preprocessor statement
----------------------------------------------
#define THE_ANSWER 42;
While all C statements end with a semicolon, preprocessor statements
(those starting with #) do not. The text following the name is
substituted directly into the program, unintended semicolon and all.