C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
// you can set them with #DEFINE statements (so you can change them
// as needed)
// If you plan on using them in several programs, you can place them
// in a header file
#define KIDS 3
#define FAMILY "The Peytons"
#define MORTGAGE_RATE 5.15

When you type a header file and then save it, you need to add the .h to the end of the file to make it
clear to your compiler that it is a header file, not a program. Most editors automatically add a .c to
the end of your programs if you do not specify a specific extension.


Now, this is an overly simplistic header file with only a few constants set with the, statement. These
are excellent examples of constants that are unlikely to change, but if they do change, it would be so
much better to make the change in one place instead of having to change hundreds, if not thousands, of
lines of code. If you create programs for family planning, budgeting, and holiday shopping, and you
decide to have (or accidentally have) a fourth child, you can make the change in this header file, and
then when you recompile all programs that use it, the change to 4 (or 5 , if you’re lucky enough to have
twins) will roll through all your code. A family name is unlikely to change, but maybe you refinance
your house and get a new mortgage rate that changes budgeting and tax planning.


A header file will not help you until you include it in a program, so here is a simple piece of code that
uses your newly created .h file:


Click here to view code image


// Example program #1 from Chapter 7 of Absolute Beginner's Guide to
// C, 3rd Edition
// File Chapter7ex1.c
/* This is a sample program that lists three kids and their school
supply needs, as well as cost to buy the supplies */
#include <stdio.h>
#include <string.h>
#include "Chapter7ex1.h"
main()
{
int age;
char childname[14] = "Thomas";
printf("\n%s have %d kids.\n", FAMILY, KIDS);
age = 11;
printf("The oldest, %s, is %d.\n", childname, age);
strcpy(childname, "Christopher");
age = 6;
printf("The middle boy, %s, is %d.\n", childname, age);
age = 3;
strcpy(childname, "Benjamin");
printf("The youngest, %s, is %d.\n", childname, age);
Free download pdf