Monday, February 11, 2013

Macro Rules and Example

Macro without argument example

A #define directive is many a time used to define operators as shown below:

#include<stdio.h>
#define OR ||
#define AND &&
int main()
{
 int p=10,q=20,r=30;
 if((p==10) AND (q<25 OR r>=50))
    printf("You are winner!!");
 else
    printf("You are loser!!");
 getch();
 return 0;
}

The output of above program would be:
Output of using macro in C program
Figure: Screen shot of shows macro uses in C program


A #define directive could be used even to replace a condition as:


#include<stdio.h>
#define OR ||
#define AND &&
#define RESULT ((p==10) AND (q<25 OR r>=50))
int main()
{
 int p=10,q=20,r=30;
 if(RESULT)
    printf("You are winner!!");

 else
    printf("You are loser!!");
 getch();
 return 0;
}

The output of above program would be:
Output of macro C program
Figure: Screen shot of shows macro uses in C program

A #define directive could be used to replace even an entire C statement.

#include<stdio.h>
#define DISPLAY printf("Yes, I got iT");
int main()
{
 DISPLAY;
 getch();
 return 0;
}

The output of above program would be:
Output of using macro in C program
Figure: Screen shot for macro example C program


Macro with argument example

#include<stdio.h>
#define SQUARE(p) (p*p)
int main()
{
 int n,result;
 printf("Enter any number: ");
 scanf("%d", &n);
 result = SQUARE(n);
 printf("Square of %d is %d",n,result);
 getch();
 return 0;
}

The output of above program would be:
Output of macro square C program
Figure: Screen shot of macro square C program


Keep in mind some following point, when you create macro

1. If there are two or more macro expansions then, entire macro expansions should be enclosed within parentheses.
Example:
#define SQUARE(p) p*p  //wrong 
#define SQUARE(p) (p*p)  //right

2. There should be not a blank between the macro template and its argument while defining the macro.
Example:
#define SQUARE (p) p*p  //wrong 
#define SQUARE(p) (p*p)  //right

3. Macro can be split into multiple lines, with a '\'(back slash) present at the end of each line.
Example:
#include<stdio.h>
#define MYPROG for(c=1; c<=10; c++)        \
               {                           \
                if(c==5)                   \
                   printf("Good C blog."); \
               }
int main()
{
 int c;
 MYPROG
 getch();
 return 0;
}

The output of above program would be:
Output of macro split C program
Figure: Screen shot for macro split C program


Related article:

No comments:

Post a Comment