Constants In C
ANSI C allows you to declare constants. When you declare a constant it is a bit like a
variable declaration except the value cannot be changed.
Syntax for initializing a const data type:
Const data-type variable = initial value;
const int a = 1;
const int a =2;
You can declare the const before or after the type. Choose one and stick to it. It is usual
to initialise a const with a value as it cannot get a value any other way.
The difference between a const variable and a manifest constant is that the # define
causes the preprocessor to do a search-and—replace operation through out code. This
sprinkles the literal through your code wherever it is used. On the other hand, a const
variable allows the compiler to optimize its use. This makes your code run faster
(compiler optimization is outside the scope of this course).
C provides special backslash character constants as shown below:
The # define directive is used to tell the preprocessor to perform a search-and-replace
Example: # define Pi 3.14159
# define Tax-rate 0.0735
In the example above, the preprocessor will search through the source file and replace
every instance of the token Pi with 3.14159
After performing the search and replace operation, the preprocessor removes the
# define line.
The following are two purposes for defining and using manifest constants:
(1) They improve source-code readability
(2) They facilitate program maintenance.