The directive #define is used to create symbolic constants and macros (small function type entities). The directive #define may be used in the following manner:
#define Identiiier Repiacement_text
Note that there is no semicolon at the end of line and there is at least one space between define and Identifier, and between Identifier and Replacement_text. During the preprocessor action wherever the identifier occurs in the program listing it is replaced with replacement_ text. For instance:
#define X 7.86
In this code, X is defined to be equal to constant value 7.86. Wherever X occurs in the source code, it is replaced by 7.86. The above expression is in fact equivalent to the following:
canst float X = 7.86;
Once defined as above, the value of X cannot be changed in the program unless X is first undefined to shed the previous value and is then redefined to a new value. The code is written as given below.
#define X 7.86
#undef X
#define X 9.87
Program illustrates the above discussion. PI is defined as equal to 3.141592653 then it is undefined and then redefined as equal to 3.141; area of a circle is calculated using both the values.
#include <stdio.h> #define PI 3.141592653 int main() { int R = 10; double A, B; A = PI*R*R ; printf ("Area with PI value 3.141592653 = %f\n", A); #undef PI // undefines the previous value. #define PI 3.141 B = PI*R*R; printf("Area with PI value 3.141 = %f", B); return 0; }
The output is obvious. The area represented by A is calculated with the defined value of PI =3.14159256 and then PI is undefined to shed its previous value and is redefined to the value 3.141. The area now represented by B is recalculated with PI = 3.141. However, the output is displayed according to the default precision setting in the computer (six digits after the decimal point).