|
#define |
#define is a preprocessor directive.
#define SIZE 10
defines a symbolic constant SIZE whose value is 10 .
A symbolic constant is an identifier that is replaced with replacement text by the C preprocessor before the program is compiled.
Why to use #define ?
Let say we have a constant that is repeated in our program for many times. If we think to change it we have to go over the program to change all the occurrence that the constant appear and their is a high risk of doing mistakes. Instead ,when using #define and the program is processed , all occurrences of the symbolic constant SIZE are replaced with the replacement text 10
#define is replaced before the program is compiled , so can use it in declaring arrays where we can't use variables or const.
| Initialize the elements of array s to the even integers from 2 to 20 |
| #include <stdio.h> #define SIZE 10 int main() { int s[ SIZE ], j; // used in declaration for ( j = 0; j <= SIZE - 1; j++ ) /* set the values */ s[ j ] = 2 + 2 * j; printf( "%s%13s\n", "Element", "Value" ); for ( j = 0; j < SIZE; j++ ) /* print the values */ printf( "%7d%13d\n", j, s[ j ] ); return 0; } |
Using symbolic constants to specify array sizes makes programs more scalable.
Assigning a value to a symbolic constant in an executable statement is a syntax error . A symbolic constant is not a variable. No space is reserved for it by the compiler as with variables that hold values at execution time.
Use uppercase letters for symbolic constant names.