Macro with Arguments

 



Macro
Arguments can take arguments and we use parenthesis for that, just like true functions. To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas. Let's be clear with the given example:- 

 

#define CUBE (A) A*A*A    

When we call above function  

CUBE (3) // formal argument 

3*3*3 // actual argument  

27 // output 

 

Here in the program, we have defined a CUBE with its parameter(A) and value(A*A*A), in the next line we call CUBE 3 which is a formal argument and is replaced with actual argument and we get the answer 27. In this process, the parameter value and formal argument must be the same(I.e. if there is one parameter then we are allowed to define only one formal argument) 

 

Wherever we use operators in replacement value we have to use brackets so that our answer will be correct. Let's see another example of using parenthesis in macro argument and be more clear 

 

#define CUBE (aa *a *a
CUBE(2 + 1// we use operators here
    /*
    (2 + 1) * (2 + 1) * (2 + 1) // we use brackets here because it have high precedence
    3 *3 * 3 // due to use of brackets it's first added and then multiplies.
    27 // output
    */

 

Code  


#include <stdio.h>
#include <conio.h>
#define MULT(ab) (a * b) // macro define
void main()
{
    int ans// variable declaration
    ans = MULT(510); // we can define a variable replace them with int too.
    printf(" answer is %d "ans); // (5 * 10 = 50)
    getch();
}

output  

answer is 50 

Follow our page for regular updates.

0 Comments