Using Macro Template In Macro Expansion: C Program


In this video tutorial lets see how we can make use of a macro template in a macro expansion.

Objective

We define PI in a macro, and then we use PI in expansion of another macro.

We shall also modify the same program to make use of constant M_PI present in math.h library file instead of macro template PI.

Related Read:
Preprocessors In C Programming Language
C Program To Find Area of Circle Using Macro Expansion
Macros With Arguments: C Program

Video Tutorial: Using Macro Template In Macro Expansion: C Program



YouTube Link: https://www.youtube.com/watch?v=s3bMxi6Isu8 [Watch the Video In Full Screen.]

Source Code: Using Macro Template In Macro Expansion: C Program

  1. #include<stdio.h>  
  2.   
  3. #define PI 3.14159265358979323846  
  4.   
  5. #define AREA(r) ( PI * r * r )  
  6.   
  7. int main()  
  8. {  
  9.     float r;  
  10.   
  11.     printf("Enter radius of Circle\n");  
  12.     scanf("%f", &r);  
  13.   
  14.     printf("Area of Circle is %f\n", AREA(r));  
  15.   
  16.     return 0;  
  17. }  

Output:
Enter radius of Circle
5
Area of Circle is 78.539816

In above source code, preprocessor replaces every occurrence of PI with 3.14159265358979323846 and then checks for every occurrence of AREA(r) and replaces with ( 3.14159265358979323846 * r * r ).

With this simple example I’m trying to illustrate that we can make use of Macro template inside macro expansion of another macro definition.

Using M_PI constant present in Math.h header file

  1. #include<stdio.h>  
  2. #include<math.h>  
  3.   
  4. #define AREA(r) ( M_PI * r * r )  
  5.   
  6. int main()  
  7. {  
  8.     float r;  
  9.   
  10.     printf("Enter radius of Circle\n");  
  11.     scanf("%f", &r);  
  12.   
  13.     printf("Area of Circle is %f\n", AREA(r));  
  14.   
  15.     return 0;  
  16. }  

Output:
Enter radius of Circle
5
Area of Circle is 78.539816

Note: M_PI is also a macro inside math.h library file.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *