Previous: 2.5 More C Statements
Up: 2 Basic Concepts
Next: 2.7 Summary
Previous Page: 2.5.6 More Complex Loop Constructs - Nested Loops
Next Page: 2.7 Summary
In this section we list some common problems and programming errors that beginners often make. We also suggest steps to avoid these pitfalls.
int x, y;There is no compiler error, x and y have unknown, garbage values. Be sure to initialize all variables.x = x * y;
while (x = y)
...
if (x = y)
printf("x is equal to y\n");
There will be no compiler error since any valid expression is allowed as an
if or while condition.
The expression is True if non-zero is assigned, and
False if zero is assigned. Always double check conditions to see that a correct
equality operator, ==, is used.
scanf("%d", n); /* should be &n */
Again this is not a compile time error;
the compiler will assume the value of n
is the address of an integer object and will attempt to store a value in it.
This often results in a run time addressing error.
Make sure the passed arguments
in scanf() calls
are addresses of the objects
where data is to be stored.
while (i < n)
...
i is garbage;
the while expression is evaluated with unknown results.
i = 0;
while (i < n) {
...
}
i is unchanged within the loop; it is always 0.
The result is an infinite loop.
n = 10;
i = 0;
while (i <= n) {
...
i = i + 1;
}
(i <= n) will be True for i = 0, 1, ..., 10, i.e. 11 times.
The loop is executed one more time than required.
Loop expressions should be examined for
values of loop variables at the boundaries. Suppose n is zero; should the loop
be executed? Suppose it is 1, suppose it is 10, etc.
while (x != 0) {
...
scanf("%d", &x);
}
Suppose a user types: 23r.
An integer is read by scanf() until a non-digit is
reached, in this case, until r is reached.
The first integer read will be 23.
However, the next time scanf() is executed it will
be unable to read an integer since the first
non-white space character is a non-digit. The loop will be an infinite loop.
int sum, count;
float avg;
avg = sum / count;
Suppose sum is 30 and count is 7.
The operation
sum / count will be the integer value of 30 / 7,
i.e. 4; the fractional part is truncated.
The result 4 is assigned to a float variable avg
as 4.0.
If a floating point value is desired
for the ratio of sum / count, then cast the integers to float:
avg = (float) sum / (float) count;Now, the expression evaluates to 30.0 / 7.0 whose result is a floating point value 4.285 assigned to avg