This post describes macro constants.
First, let’s briefly describe the preprocessor. The preprocessor runs before the program is compiled and processes preprocessor directives that begin with #. Examples include #define and others.
#define is a command that replaces a string (name) with a constant value. Constants defined using this command are called “macro constants.”
For example, if you define it as follows:
#define MAX_USERS 100
After this, if you write MAX_USERS in the program, the preprocessor will replace it with 100. This makes the code easier to understand and allows you to manage the value in one place.
Next, I will describe the purpose of using macro constants.
Improved readability
This is used to make the meaning of constants easier to understand.
#define iPI 3.14159
double area = iPI * r * r;
Improved maintainability
If the same value is used in multiple places, you only need to change the definition.
#define iBUFF_SIZE 128
unsigned char BUFF[iBUFF_SIZE]
for( i=0 ; i<iBUFF_SIZE ; i++ )
{
sum = sum + BUFF[i]:
Elimination of unclear numerical values
If the meaning of the numerical values is unclear, use macro constants with labels to make the meaning easier to understand.
#define iSECOND_IN_A_DAY 60 * 60 *24 /* 86400s/Day */
if( s < iSECOND_IN_A_DAY )
{
Conditional compilation specifications
Used when switching program code with conditional compilation.
#define iTEST 1 /* Debug SW 0:OFF 1:ON */
#ifdef iTEST == 1
printf( "integer: %d", x); /* Debug Code */
#endif