C Programming language

adplus-dvertising
Macros in C
Previous Home Next

Macros with argument

The macros that we have used so far are called simple macros. Macros can have arguments, just as functions can. Here is an example that illustrates this fact.

#define Area) ( 3.14 * x * x )
main( )
{
float r1 = 6.25, r2 = 2.5, a ;
a = AREA ( r1 ) ;
printf ( "\area of circle = %f", a ) ;
a = AREA ( r2 ) ;
printf ( "\area of circle = %f", a ) ;
}

Here’s the output of the program...
Area of circle = 122.656250
Area of circle = 19.625000

In this program wherever the pre-processor finds the phrase Area) it expands it into the statement ( 3.14 * x * x ). However, that’s not all that it does. The x in the macro template Area) is an argument that matches the x in the macro expansion ( 3.14 * x * x ). The statement AREA(r1) in the program causes the variable r1 to be substituted for x. Thus the statement AREA(r1) is equivalent to: ( 3.14 * r1 * r1 ).

After the above source code has passed through the pre-processor, what the compiler gets to work on will be this:

main( )
{
float r1 = 6.25, r2 = 2.5, a ;
a = 3.14 * r1 *r1 ;
printf ( "Area of circle = %f\n", a ) ;
a = 3.14 *r2 * r2 ;
printf ( "Area of circle = %f", a ) ;
}
Here is another example of macros with arguments:
#define ISDIGIT(y) ( y >= 48 && y <= 57 )
main( )
{
char ch ;
printf ( "Enter any digit " ) ;
scanf ( "%c", &ch ) ;
if ( ISDIGIT ( ch ) )
printf ( "\nYou entered a digit" ) ;
else
printf ( "\nIllegal input" ) ;
}

Macros vs Function

In a macro call the pre-processor replaces the macro template with its macro expansion, in a stupid, unthinking, literal way. As against this, in a function call the control is passed to a function along with certain arguments, some calculations are performed in the function and a useful value is returned back from the function.

Usually macros make the program run faster but increase the program size, whereas functions make the program smaller and compact.

If we use a macro hundred times in a program, the macro expansion goes into our source code at hundred different places, thus increasing the program size. On the other hand, if a function is used, then even if it is called from hundred different places in the program, it would take the same amount of space in the program.

Previous Home Next