Thursday, 10 February 2011

50. What is macros in C

A macro is a fragment of code which has been given a name. When we use the name of macro in program, it is replaced by the contents of the macro. You may define any valid identifier as a macro, even if it is a c keyword. There are two types of macros. One is object-like macros and another is function-like macros. Object-like macros do not take parameters; function-like macros do. The generic syntax for declaring an identifier as a macro of each type is:
For object-like macros:
 #define <identifier> <replacement token list>
For example:
#include<stdio.h>
#include<conio.h>
#define sum a+b
void main()
{
Clrscr();
int a=5,b=10,c;
c=sum; //if we give the semicolon (;)when we define the macro; then we cannot give the semicolon when we write the name of identifier. If we give the semicolon when we define the macro, then we give the semicolon when we write the name of identifier in program
printf(“The sum of a+b is: %d”,c);
getch();}
For function-like macros:
#define <identifier> (<parameter list>) <replacement token list>
For example:   
#include<stdio.h>
#include<conio.h>
#define square(x) x*x;
Void main()
{
Clrscr();
int i=2,j;
j=square(i) //Here is no semicolon because I give the semicolon when I define the macros.
printf(“The value of j is: %d”,j);
getch();
}
 The #undef directive removes the definition of a macro.
Written by arnob;

No comments:

Post a Comment