Wednesday, 10 December 2014

Macros in c++ with example

Macros in C++ with Examples: 

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
#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 the small example:
#define MIN(i,j) (i < j ? i : j)

Disadvantages of the macros are they do not perform any type 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
#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:
Macro MIN(x,y) = 10

One of the common mistakes we make when we use Macro is to forget what Macro is suppose to do. In the following example, if we miss parenthesis around it, it will give us unexpected result.
#define SQUARE(i) (i*i)

Here is the example which may give unexpected results:
#include <stdio.h>
#define SQUARE (i)(i*i)
int main()
    int i, j = 4;
    i = SQR(j+2);
    printf("The value of i = %d\n", i); 
    getchar ();
    return 0;

Compile and run the above program we may get the unexpected results
The macro should be like below
#define SQUARE (i)((i)*(i)) 

To overcome the problems that are come with the macros, the only solution is inline functions.

No comments: