A macro is defined as the piece of code that is replaced by the value of the macro in the program. We can define the macro by using the #define
directive. Whenever a compiler encounters the macro name, it replaces it with the definition of the macro. There is no need to terminate the macro definition using a semi-colon (;
).
Let’s discuss the basic example to understand this concept:
#include <iostream>using namespace std;#define Area 10int main(){// Print the value of macro definedcout << "The value of AREA is :" << Area;return 0;}
Line 3: We define the value of the macro.
Lines 4–10: We write the main’s driver program. This prints the value of the defined macro.
There are four types of macros:
Chain macros
Object-like macros
Function-like macros
Multi-line macros
Chain macros are defined as the macros inside the macros. The parent macro is expanded in the first instance and then the child macro is expanded.
#include <iostream>using namespace std;#define Vehicles CARS#define CARS 5int main(){cout << "I have " << CARS << " Cars";return 0;}
Lines 3–4: We define the parent and the child macros.
Line 7: Here, the vehicle
is expanded to produce CARS
. After this, the macro is expanded to produce the outcome.
An object-like macro is defined as the simple identifier that is replaced by the code fragment. It looks like an object in code. Therefore, it is called an object-like macro.
#include <iostream>using namespace std;#define DATE 15int main(){cout << "The deadline is " << DATE << "-MAY-2022";return 0;}
Line 3: We define the value of the macro.
Lines 4–8: We are writing the main’s driver program. This prints the value of macro defined.
Function-like macros work the same as the function call. It is used to replace the entire code instead of the function name.
#include <iostream>using namespace std;#define PI 3.1416#define AREA(r) (PI*(radius)*(radius))int main() {float radius = 7;cout<<"Area of Circle with Radius " << radius <<": "<< AREA(r);return 0;}
Lines 3–4: We define the function-like macros.
Lines 6–13: We are writing the program’s main driver. This performs the function and prints the value of the defined macro.
An object-line macro may be of multiple lines. Therefore, if we want to create a multi-line macro, we have to use the backslash-newline.
#include <iostream>using namespace std;#define table 2, \4, \6, \8, \10, \12, \14, \16, \18, \20, \int main(){int arr[] = { table };printf("The table of 2 is :\n");for (int i = 0; i < 10; i++) {cout << arr[i] << ' ';}return 0;}
Lines 3–12: We define the multi-line macros.
Lines 14–23: We make an array in which we call multi-line macros. Then, we print the elements of that array.