Macros can be implemented using #define. When the call to the macro occurs, the code of the macro will substitute in the source code before compilation.
Syntax of the macro is
1 |
#define LIMIT 10 |
1 |
#define macroname(arg1, arg2…) expression |
NOTE: Do not leave the space between the function and the parenthesis. The parenthesis should start immediately after the macro name.
Below is a small example:
1 |
#define MIN(i,j) (i < j ? i : j) |
The disadvantages of the macros are they do not perform any type of checking.
But Macros directly substitute their code, they reduce the overhead of a function call.
Let us see the below example that helps the use of the macros
1 2 3 4 5 6 7 8 9 10 |
#define MIN(a,b) (a < b ? a : b) #include <iostream> using namespace std ; int main() { int x = 10, y = 20; cout << "Macro MIN(x,y) = " << MIN(x,y) << endl; getchar (); return 0; } |
Output is:
1 |
Macro MIN(x,y) = 10 |
One of the common mistakes we make when we use Macro is to forget what Macro is supposed to do. In the following example, if we miss parenthesis around it, it will give us unexpected results.
1 |
#define SQUARE(i) (i*i) |
The macro should be like below
1 |
#define SQUARE (i)((i)*(i)) |
To overcome the problems that are come with the macros, the only solution is inline functions