Macros and Functions

While writing the macro, you have to write the macro body carefully because the macro just indicates replacement, not the function call.

#include <stdio.h>
#define add(x1, y1)  x1+y1   //E
#define mult(x2,y2) x2*y2   //F
int main ()
{
    int a,b,c,d,e;
    a = 2;
    b = 3;
    c = 4;
    d = 5;
    e = mult(add(a, b), add(c, d)); //A

    // mult(a+b, c+d)               //B
    // a+b * c+d                    //C

    printf ("The value of e is %d\n", e);
    getchar();
    return 0;
}

Explanation

  1. Statement E indicates a macro for adding two numbers.
  2. Statement F indicates a macro for multiplying two numbers.
  3. Statement A indicates a macro that is supposed to add two numbers and then multiply two numbers. In this case, it is supposed to perform the calculation (2+3) * (4+5).
  4. The actual expansion of macro adds is given in statement B.
  5. The final expansion of mult gives the expansion a+b * c+d, which is erroneous.
  6. The final value of e is 17, which is not correct.
  7. To get the correct value, use the following definition:
#define add(x1, y1) (x1+y1)
#define mult(x2, y2) (x2*y2)

 
Point to Remember
 
1.While using the macro, you have to write the expression correctly. You can use parentheses to give the correct meaning to the expression.