Programming in C

(Barry) #1
The #includeStatement 315

#include <stdio.h>
#include "metric.h"


int main (void)
{
float liters, gallons;


printf ("*** Liters to Gallons ***\n\n");
printf ("Enter the number of liters: ");
scanf ("%f", &liters);

gallons = liters * QUARTS_PER_LITER / 4.0;
printf ("%g liters = %g gallons\n", liters, gallons);

return 0;
}


Program 13.3 Output


Liters to Gallons


Enter the number of liters: 55.75
55.75 liters = 14.73 gallons.


The preceding example is a rather simple one because it only shows a single defined
value (QUARTS_PER_LITER) being referenced from the included file metric.h.
Nevertheless, the point is well made: After the definitions have been entered into
metric.h, they can be used in any program that uses an appropriate #include
statement.
One of the nicest things about the include file capability is that it enables you to cen-
tralize your definitions, thus ensuring that all programs reference the same value.
Furthermore, errors discovered in one of the values contained in the include file need
only be corrected in that one spot, thus eliminating the need to correct each and every
program that uses the value. Any program that references the incorrect value simply
needs to be recompiled and does not have to be edited.
You can actually put anything you want in an include file—not just #definestate-
ments, as might have been implied. Using include files to centralize commonly used pre-
processor definitions, structure definitions, prototype declarations, and global variable
declarations is good programming technique.
One last point to be made about include files in this chapter: Include files can be
nested.That is, an include file can itself include another file, and so on.


Program 13.3 Continued

Free download pdf