C Programming (Turbo C++ Compiler) Use of #define macro
#define is a macro and it is used widely in C whenever required. All #define values get replaced with actual values after compilation. Then one might ask a question, why do we need #define macro? The answer is program clarity and ease of maintenance.
Another place #define are used widely is with project configuration. For example, You can have different code for _DEBUG and NDEBUG (release) mode configuration.
you can check like,
#if defined(_DEBUG)
printf("working under debug mode");
#endif
Look the following simple example.
int _tmain(int argc, TCHAR* argv[])
{
int arrayData[10];
int CloneData[10];
for(int i = 0; i < 10; i++)
{
scand("%d",&arrayData[i]);
}
for(int i = 0; i < 10; i++)
{
CloneData[i] = arrayData[i];
}
for(int i = 0; i < 10; i++)
{
printf("%d\n", CloneData[i]);
}
int a = 10 + 20 + 30;
int b = a;
return 0;
}
The number 10 is used in 6 places in the function out of which 5 places are the same purpose indicating the number of elements. If we have to change the number of elements it to 20, then we have to make changes in 5 places out of 6 places where 10 is used.
If we have used #define macro, it would be very easy to change. #define is used for clarity and ease of program maintenance.
Look at the source code section for #define example.
Source Code
#define MAX_ELEMENTS 10
int _tmain(int argc, TCHAR* argv[])
{
int arrayData[MAX_ELEMENTS];
int CloneData[MAX_ELEMENTS];
for(int i = 0; i < MAX_ELEMENTS; i++)
{
scanf("%d", &arrayData[i]);
}
for(int i = 0; i < MAX_ELEMENTS; i++)
{
CloneData[i] = arrayData[i];
}
for(int i = 0; i < MAX_ELEMENTS; i++)
{
printf("%d\n", CloneData[i]);
}
int a = 10 + 20 + 30;
int b = a;
return 0;
}
Output
10
20
30
40
50
60
70
80
90
100
10
20
30
40
50
60
70
80
90
100
|