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

(Romina) #1
Note

The Draw Poker program in Appendix B, “The Draw Poker Program,” includes
several header files because it uses lots of built-in functions. Notice the placement of
the #include statements; they come before main().

Defining Constants


The #define preprocessor directive defines constants. A C constant is really the same thing as a
literal. You learned in Chapter 2, “Writing Your First C Program,” that a literal is a data value that
doesn’t change, like the number 4 or the string "C programming". The #define preprocessor
directive lets you give names to literals. When you give a name to a literal, the named literal is known
in C terminology as a named constant or a defined constant.


Warning

In Chapter 5, “Adding Variables to Your Programs,” you learned how to define
variables by specifying their data types and giving them a name and an initial value.
Constants that you define with #define are not variables, even though they
sometimes look like variables when they are used.

Here is the format of the #define directive:


Click here to view code image


#define CONSTANT constantDefinition

As with most things in C, using defined constants is easier than the format leads you to believe. Here
are some sample #define directives:


#define AGELIMIT 21
#define MYNAME "Paula Holt"
#define PI 3.14159

In a nutshell, here’s what #define tells C: Every place in the program that the CONSTANT appears,
replace it with the constantDefinition. The first #define just shown instructs C to find
every occurrence of the word AGELIMIT and replace it with a 21. Therefore, if this statement
appeared somewhere in the program after the #define:


if (employeeAge < AGELIMIT)

the compiler acts as if you typed this:


if (employeeAge < 21)

even though you didn’t.

Free download pdf