Take a look at the program ``circle.c'' in your ``examples'' directory
(or view it directly). Can
you think of a way of making it more readable?
Click here for the answer
One approach to solving this problem would be to declare a variable called PI
and assign it an initial value of 3.14159. We could then replace both
occurrences of 3.14159 with PI. What is misleading about doing this?
Click here for the answer
Try the following modification instead. On a line before the ``main''
procedure, put the line
#define PI 3.14159
and then replace both occurrences of 3.14159 with PI. The program should
compile and run exactly as before.
The #define line is a directive to the preprocessor to replace every
occurrence of PI in the file with 3.14159. That is, before the compiler even
sees the program, every occurrence of PI has been replaced with 3.14159. (The
change is not made to the permanent copy of the file, but is made temporarily
for the benefit of the compiler.)
Now, what do you suppose would happen if you tried to change the value of PI in
the program? Right after the declaration of ``r'' in ``main'', try putting in
an assignment statement that changes the value of PI to 3.14. What happens
when you try to compile it?
Click here for the answer
This method of defining symbolic constants is actually kind of old fashioned.
Try replacing the definition of PI with the executable C statement
const float PI = 3.14159;
The keyword ``const'' tells the compiler that the value of PI must never be
modified. Now when you compile the program, what error message do you get
concerning the assignment that you added?
Click here for the answer
The moral of the story is that if you want to define a symbolic constant, use
the ``new-fashioned'' way instead of using #define. If you'd like to
know a little bit more about how the ``const'' keyword works, take a look at
section 5.8 of the book.
Hamlet Project
hamlet@cs.utah.edu