Common Programming Mistakes 499
- Forgetting to reserve an extra location in an array for the terminating null character of a
string.
Remember to declare character arrays so that they are large enough to contain the
terminating null character. For example, the character string "hello"would
require six locations in a character array if you wanted to store a null at the end. - Confusing the operator ->with the operator .when referencing structure members.
Remember, the operator .is used for structure variables, whereas the operator ->
is used for structure pointervariables. So, if xis a structure variable, the notation
x.mis used to reference the member mof x. On the other hand, if xis a pointer to
a structure, the notation x->mis used to reference the member mof the structure
pointed to by x. - Omitting the ampersand before nonpointer variables in a scanfcall.
Example
int number;
...
scanf ("%i", number);
Remember that all arguments appearing after the format string in a scanfcall
must be pointers.
- Using a pointer variable before it’s initialized.
Example
char char_pointer;
char_pointer = 'X';
You can only apply the indirection operator to a pointer variable afteryou have set
the variable pointing somewhere. In this example,char_pointeris never set
pointing to anything, so the assignment is not meaningful.
- Omitting the breakstatement at the end of a case in a switchstatement.
Remember that if a breakis not included at the end of a case, then execution
continues into the next case. - Inserting a semicolon at the end of a preprocessor definition.
This usually happens because it becomes a matter of habit to end all statements
with semicolons. Remember that everything appearing to the right of the defined
name in the #definestatement gets directly substituted into the program. So the
definition
#define END_OF_DATA 999;
leads to a syntax error if used in an expression such as
if ( value == END_OF_DATA )
...
23 0672326663 AppD 6/10/04 2:00 PM Page 499