Previous: 3.5 Debugging Guidelines
Up: 3 Designing Programs Top Down
Next: 3.7 Summary
Previous Page: 3.5 Debugging Guidelines
Next Page: 3.7 Summary
This section contains a list of common errors made by programmers - things to watch out for in your programming.
flag = scanf("%d", &n);
while (n != EOF) /* should be: while (flag != EOF) */
...
The value read is stored at the address given by &n,
i.e. it is stored in n.
The statement scanf("%d", &n)
evaluates to a returned value which is either the number of
data items read or EOF.
In the above case, if an integer data item is read, the
value returned will be 1. If no data item is read, scanf() returns EOF.
The value returned by scanf() is stored in the variable flag,
NOT in n. Test flag for EOF,
NOT n.
#include <stdio.h>
#define TRUE 1
main()
{ int x, square(int x);
x = 3;
square(x); /* x cannot be unchanged by square() */
printf("x = %d\n", x); /* prints: x = 3 */
}
int square(int x) /* x is a new object, with initial value */
/* passed by an argument in the function call */
{
x = x * x; /* new x is changed */
return TRUE; /* a value is returned as the value of square() */
}
The variable x in main()
is a different object from x in square(). The value of
the local cell, x,
is changed in square(),
but that does not affect the cell x in main().
The cell, x, in main() will still
have the value 3 after the function
call to square(). If main() needs the squared value of x,
then square() should return the squared value of x,
NOT TRUE. This returned value should be saved in a local variable
in main(). For example, if the return statement
in square() is:
return x;then the returned value can be saved in main():
x = square(x);