Programming in C

(Barry) #1
Common Programming Mistakes 499


  1. 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.

  2. 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.

  3. 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.


  1. 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.


  1. 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.

  2. 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

Free download pdf