Previous: 5.4 Operators and Expression Evaluation
Up: 5 Numeric Data Types and Expression Evaluation
Next: 5.6 Summary
Previous Page: 5.4.3 Some New Operators
Next Page: 5.6 Summary

5.5 Common Errors

  1. A result may be outside the range of values possible for a given data type. Use a data type with greater range and/or precision.

  2. Prototypes are not declared; instead, default integer type declaration is assumed for functions. If there is no prototype declaration for a function and if the argument in the function call is a float, it is converted to double. If the formal parameter in the function definition is declared as a float, there is a possible mismatch. A double object passed as an argument might be accessed as a float resulting in a possible wrong value. The actual situation depends on the compiler. Here is an example:
    /*   File: default.c
              Program illustrates problems with default declarations for functions.
         */
         #include <stdio.h>
         main()
         {    float x;
    

    x = 3.0; printf("Truncated Square of %f = %d\n", x, trunc_square(x)); }

    int trunc_square(float z) { return (int) (z * z); }

    The function trunc_square() returns integer type and main() uses the default declaration for trunc_square(). The float argument, x in the function call in main() is converted to double. But trunc_square() declares a float formal parameter, z. An attempt will be made to access a double object as a float. The function may not access the correct value passed as an argument. Thus, it is always best to use function prototypes to avoid confusion.

  3. An expression is written without consideration of precedence and associativity of the operators. For example,
    while (x = scanf("%d", &n) != EOF)
              ...
    Wrong! The scanf() value is compared first with EOF and the result of the comparison is assigned to x. Using parentheses:
    while ((x = scanf("%d", &n)) != EOF)
              ...
    x is assigned the value returned by scanf(), and the value of x is then compared with EOF. Examples where associativity must be considered include:
    a = 10; b = 5; c = 20; d = 4;
    

    a - b - c is -15 a / b / c / d is 0 a % d % b % c is 2

  4. Increment and decrement operators are used incorrectly. Remember that postfix implies increment/decrement after evaluation and prefix implies increment/decrement before evaluation.



Previous: 5.4 Operators and Expression Evaluation
Up: 5 Numeric Data Types and Expression Evaluation
Next: 5.6 Summary
Previous Page: 5.4.3 Some New Operators
Next Page: 5.6 Summary

tep@wiliki.eng.hawaii.edu
Wed Aug 17 08:40:40 HST 1994