Macros are snippets of code that get processed before compilation. This is done by the C preprocessor, #define statements are macros. Take a look at this piece of code:
Example 10-1. box_of_stars.c
#define SIZE_OF_SQUARE 4 int main() { int i, j; for(i = 0; i < SIZE_OF_SQUARE; i++) { for(j = 0; j < SIZE_OF_SQUARE; j++) { printf("*"); // print an asterisk for each column } printf("\n"); // and a newline at the end of each row } }
**** **** **** ****The C preprocessor simply replaces the macro SIZE_OF_BOX with the value ``4''. This very useful for two reasons:
firstly the size of the box can be changed by just editing one line. This isn't a huge advantage in the above example as there are just two uses of SIZE_OF_BOX but in larger programs this make life much easier and removes the possibility of forgetting to change one of the values.
Secondly it makes the code more readable, meaningful names can be given to values such as #define PI 3.142857143.