Programming in C

(Barry) #1
The #defineStatement 303

int main (void)
{
double area (double r), circumference (double r),
volume (double r);


printf ("radius = 1: %.4f %.4f %.4f\n",
area(1.0), circumference(1.0), volume(1.0));

printf ("radius = 4.98: %.4f %.4f %.4f\n",
area(4.98), circumference(4.98), volume(4.98));

return 0;
}


Program 13.2 Output


radius = 1: 3.1416 6.2832 4.1888
radius = 4.98: 77.9128 31.2903 517.3403


The symbolic name PIis defined as the value 3.141592654 at the beginning of the pro-
gram. Subsequent use of the name PIinside the area, circumference, and volume func-
tions has the effect of causing its defined value to be automatically substituted at the
appropriate point.
Assignment of a constant to a symbolic name frees you from having to remember the
particular constant value every time you want to use it in a program. Furthermore, if you
ever need to change the value of the constant (if, perhaps, you find out that you are
using the wrong value, for example), you only have to change the value in one place in
the program: in the #definestatement.Without this approach, you would have to other-
wise search throughout the program and explicitly change the value of the constant
whenever it was used.
You might have realized that all the defines you have seen so far (YES,NO,NULL, and
PI) have been written in capital letters.The reason this is done is to visually distinguish a
defined value from a variable. Some programmers adopt the convention that all defined
names be capitalized, so that it becomes easy to determine when a name represents a
variable and when it represents a defined name. Another common convention is to pre-
fix the define with the letter k. In that case, the following characters of the name are not
capitalized.kMaximumValuesand kSignificantDigitsare two examples of defined
names that adhere to this convention.


Program Extendability


Using a defined name for a constant value helps to make programs more readily extend-
able. For example, when you define an array, you must specify the number of elements in


Program 13.2 Continued

Free download pdf