Forgetting to Include Header Files for Library Functions

Because they contain needed function prototypes, it's important to include the correct header files when using QuickC library functions:

main()

{

double val = sqrt( (double) 10 );

printf( "square root of 10 = %le\n", val );

}

The program above calls the library function sqrt, which calculates a square root. Most of the program is correct. When passing the value 10 to sqrt, it casts the argument as a double, the type sqrt expects. The return value from sqrt is assigned to a double variable, too.

Unfortunately, the program still gives the wrong output. The square root of 10 is not 171 (1.710000e+002 in exponential notation):

square root of 10 = 1.710000e+002

Summary: Function prototypes can prevent unexpected type conversions.

Because the program has no prototype for the sqrt function, sqrt has the int return type by default. The value returned by sqrt undergoes an unexpected type conversion—from type double to int—and becomes garbage.

This problem is easily solved. Simply include the standard header file that contains the prototype for sqrt:

#include <stdio.h>

#include <math.h>

main()

{

double val = sqrt( (double) 10 );

printf( "square root of 10 = %le\n", val );

}

Now the program works correctly:

square root of 10 = 3.162278e+000

If you're not sure which header file a library function needs, take advantage of QuickC's online help. (Put the cursor on the function name and press F1.) If the function needs a header file, the file name appears in an #include directive above the function prototype.