Macro Expansion

 Macros are pieces of code in a program that is given some name. Whenever this name is encountered by the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro. 

  • There are two types of macros - one which takes the argument and another which does not take any argument.
  • Values are passed so that we can use the same macro for a wide range of values.


SIMPLE MACRO

    Syntax:
    #define name replacement text

    Where,
    name – it is known as the micro template.
    replacement text – it is known as the macro expansion.

  • A macro name is generally written in capital letters.
  • If suitable and relevant names are given macros increase the readability.
  • If a macro is used in any program and we need to make some changes throughout the program we can just change the macro and the changes will be reflected everywhere in the program.
Example

#include <stdio.h>
#include<conio.h>
 
// macro definition
#define LIMIT 8
int main()
{
    for (int i = 0; i < LIMIT; i++) {
        printf("%d \n",i);
    }
    getch();
    return 0;
}

Output
0
1
2
3
4
5
6
7


In the above program, when the compiler executes the word LIMIT, it replaces it with 8. The word ‘LIMIT’ in the macro definition is called a macro template and ‘8’ is macro expansion. 

Note: There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a semi-colon to end.


Macros With Arguments: We can also pass arguments to macros. Macros defined with arguments work similarly to functions. Let us understand this with a program: 

#include <stdio.h>
#include<conio.h>

// macro with parameter 
#define AREA(l, b) (l * b)
int main()
{
    int l1 = 10, l2 = 5, area;
 
    area = AREA(l1, l2);
 
    printf("Area of rectangle is: %d", area);
    getch();
    return 0;
}

Output
Area of rectangle is : 50

We can see from the above program that whenever the compiler finds AREA(l, b) in the program, it replaces it with the statement (l*b). Not only this, but the values passed to the macro template AREA(l, b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to 10*5.



#include <stdio.h>
#include<conio.h>
  
#define MIN(a,b) ((a)<(b)?(a):(b))  
int main() {  
   printf("Minimum between 10 and 20 is: %d\n", MIN(10,20)); 
   getch();
   return 0;   
}  

Output
Minimum between 10 and 20 is : 10

No comments:

Post a Comment