Wednesday, 27 February 2013

What Is Micro Substitution

The #define directive is the most common processor directive, which tell the Processor to replace every occurrence of a particular character string ( that is, a macro name ) with a specified value ( that is, macro body).

The syntax for the #define directive is:

 #define Macro_name macro_body


Here macro name is an identifier that can contain letters, numerals, or underscores. Macro_body may be a string  or a data item, which is used to substitute each macro_name found in the program. As mentioned earlier, the operation to replace occurrences of the macro_ name with the value specified by the macro_ body is known as macro substitution or macro expansion. The value in the macro body specified by a #define directive can be any.character string or number.

Example: #define NAME  "to more"

Here NAME will be replaced by "to more." .

Other examples:

#define MUX  (8*8)

On the other hand, we can use #undef directive to remove the definition of a macro name who has been previously defined.

Syntax:

 #undef macro_name

Here macro_name is an identifier that has been previously defined by a #define directive.The #undef directive "undefined" a macro name.For instance the following segment of code.



#define NAME "author"

printf(" I am of %s.\n ",NAME);
  
#undef NAME 

It defines the macro name NAME first, and uses the macro name for the print( function  then it removes the macro name.

Defining the macro with arguments:
You can specify one or more arguments to a macro name defined by the #define directive, so that the macro name can be treated like a simple function that accepts arguments.

 #define MUL(val1,val2) ((val1)*(val2))

When the following statement.

 A result= MUL(2,3)+10;

The  preprocessor substitute the expression 2 for val1 and 3 for val2  and the produces the following statement.

 result=((2)*(3))+10;

/*Program to understand macros with arguments*/




#include <studio.h>
#define SUM(x,y) ((x)+(y))
#define PROD(x,y) ((x)+(y))
main()
{

     int l,m,i,j,a=5,b=3;
     float p,q;
     l=SUM(4,6)
     m=PROD(a,b)
     i=SUM(4,6)
     j=PROD(4,6)
     p=SUM(2.2,3.4);
    q=PROD(2.2,3.4);
    printf("i=%d,m=%d,i=%d,j=%d,p=%0.1f,q=%0.1f\n",I,m,I,j,p,q); 

}


Output :



l=8,m=15,i=10,j=24,p=5.6,q=7.5

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More