Pages

Thursday, December 16, 2010

Macros with Arguments

Like functions, macros too can have arguments. If a macro has been defined with arguments, the same should be passed while using it.

Example 1 : A macro to find out square of a number

#define SQUARE(no) (no * no )
void main( )
{
int num=4,sq;
sq = SQUARE (num) ;
printf ( "\nArea of circle = %d",sq) ;
}


In the above program, when the statement "SQUARE(no)" is encountered by the preprocessor it expands it to (no * no).  The "no" in the macro template is an argument that matches the no in the macro expansion ( no * no ). When the statement "SQUARE(no)" is written it copies the value of "num" to "no". Therefore the statment "SQUARE(num)" translates to "(num*num)". When the preprocessor has done its bit, the code is passed on to the compiler. The above program will be compiled like this

#define SQUARE(no) (no * no )
void main( )
{
int num=4,sq;
sq = num*num ;
printf ( "\nArea of circle = %d",sq) ;
}


Example 2 : To check if the given number is positive or negative


#include
#define CHECKPOS(n) (n>0)

void main()
{
    int value;
    printf("\nEnter a number : ");
    scanf("%d",&value);
    if(CHECKPOS(value))
        printf("\nPOSITIVE");
    else
        printf("\nNEGATIVE");
}



Example 3 : To check if the given number is an even or odd number.

#include
#define ISEVEN(num) (num%2==0)
void main()
{
    int no=1;
    if(ISEVEN(no))
        printf("\nEVEN");
    else
        printf("\nODD");
    }
}


Points to remember

1. Make sure that the macro expansion(body) is enclosed within a pair of circular brackets. For example, in the example 1 above don't write

#define SQUARE(no)  no * no // incorrect
 
Instead write

#define SQUARE(no) (no * no ) // correct
2. We can break a macro into two or more lines using a backslash at the end of the line.For example, the example 3 can be written as
#define ISEVEN(num)\
(num%2==0)

3.  Don't put a space between the macro and its value. For instance in the example 1 above don't put a space between SQUARE(macro name) and no (macro value)
// incorrect because of a space after SQUARE
#define SQUARE (no) (no * no )
// correct, no spaces.
#define SQUARE(no) (no * no)

0 comments:

Post a Comment