Programming in C

(Barry) #1

302 Chapter 13 The Preprocessor


By including a definition such as
#define NULL 0
in a program, you can then write more readable statements, such as
while ( listPtr != NULL )
...
to set up a whileloop that will execute as long as the value of listPtris not equal to
the null pointer.
As another example of the use of a defined name, suppose you want to write three
functions to find the area of a circle, the circumference of a circle, and the volume of a
sphere of a given radius. Because all these functions need to use the constant π, which is
not a particularly easy constant to remember, it makes sense to define the value of this
constant once at the start of the program and then use this value where needed in each
function.^3
Program 13.2 shows how a definition for this constant can be set up and used in a
program.

Program 13.2 More on Working with Defines
/* Function to calculate the area and circumference of a
circle, and the volume of a sphere of a given radius */

#include <stdio.h>

#define PI 3.141592654

double area (double r)
{
return PI * r * r;
}

double circumference (double r)
{
return 2.0 * PI * r;
}

double volume (double r)
{
return 4.0 / 3.0 * PI * r * r * r;
}

3.The identifier M_PIis already defined for you in the header file <math.h>. By including that
file in your program, you can use it directly in your programs.
Free download pdf