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

(Romina) #1
Tip

Use uppercase letters for the defined constant name. This is the one exception in C
when uppercase is not only used, but recommended. Because defined constants are not
variables, the uppercase lets you glance through a program and tell at a glance what is
a variable and what is a constant.

Assuming that you have previously defined the constant PI, the uppercase letters help keep you from
doing something like this in the middle of the program:


Click here to view code image


PI = 544.34; /* Not allowed */

As long as you keep defined constant names in upper case, you will know not to change them because
they are constants.


Defined constants are good for naming values that might need to be changed between program runs.
For example, if you didn’t use a defined constant for AGELIMIT, but instead used an actual age limit
value such as 21 throughout a program, if that age limit changed, finding and changing every single
21 would be difficult. If you had used a defined constant at the top of the program and the age limit
changed, you’d only need to change the #define statement to something like this:


#define AGELIMIT 18

The #define directive is not a C command. As with #include, C handles your #define
statements before your program is compiled. Therefore, if you defined PI as 3.14159 and you used
PI throughout a program in which you needed the value of the mathematical pi (π), the C compiler
would think you typed 3.14159 throughout the program when you really typed PI. PI is easier to
remember (and helps eliminate typing mistakes) and is clearer to the purpose of the constant.


As long as you define a constant with #define before main() appears, the entire program will
know about the constant. Therefore, if you defined PI to be the value 3.14159 before main(), you
could use PI throughout main() and any other functions you write that follow main(), and the
compiler would know to replace PI with 3.14159 each time before compiling your program.


Building a Header File and Program


The best way to ensure that you understand header files and defined constants is to write a program
that uses both. So fire up your editor and let’s get typing!


First, you create your first header file:


Click here to view code image


// Example header program #1 from Chapter 7 of Absolute Beginner's
// Guide to C, 3rd Edition
// File Chapter7ex1.h
// If you have certain values that will not change (or only change
// rarely)
Free download pdf