Programming in C

(Barry) #1
498 Appendix D Common Programming Mistakes

If squareRootis defined later in the program, or in another file, and is not explic-
itly declared otherwise, the compiler assumes that the function returns an int.
Furthermore, the compiler converts floatarguments to double,and _Bool,char,
and shortarguments to int. No other conversion of arguments is done.
Remember, it’s always safest to include a prototype declaration for allfunctions
that you call (either explicitly yourself or implicitly by including the correct head-
er file in your program), even if they’re defined earlier.


  1. Confusing the precedences of the various operators.
    Examples
    while ( c = getchar () != EOF )
    ...
    if ( x & 0xF == y )
    ...


In the first example, the value returned by getcharis compared against the value
EOFfirst.This is because the inequality test has higher precedence than the assign-
ment operator.The value that is therefore assigned to cis the TRUE/FALSE result
of the test: 1 if the value returned by getcharis not equal to EOF, and 0 other-
wise. In the second example, the integer constant 0xFis compared against yfirst
because the equality test has higher precedence than any of the bitwise operators.
The result of this test (0 or 1) is then ANDed with the value of x.


  1. Confusing a character constant and a character string.
    In the statement
    text = 'a';


a single character is assigned to text. In the statement
text = "a";

a pointer to the character string "a"is assigned to text.Whereas, in the first case,
textis normally declared to be a charvariable, in the second case, it should be
declared to be of type "pointer to char".


  1. Using the wrong bounds for an array.
    Example
    int a[100], i, sum = 0;
    ...
    for ( i = 1; i <= 100; ++i )
    sum += a[i];


Valid subscripts of an array range from 0 through the number of elements minus
one.Therefore, the preceding loop is incorrect because the last valid subscript of a
is 99 and not 100.The writer of this statement also probably intended to start with
the first element of the array; therefore,ishould have been initially set to 0.

23 0672326663 AppD 6/10/04 2:00 PM Page 498

Free download pdf