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 https://www.youtube.com/watch?v=s3bMxi6Isu8]

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

#include<stdio.h>

#define PI 3.14159265358979323846

#define AREA(r) ( PI * r * r )

int main()
{
    float r;

    printf("Enter radius of Circle\n");
    scanf("%f", &r);

    printf("Area of Circle is %f\n", AREA(r));

    return 0;
}

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

#include<stdio.h>
#include<math.h>

#define AREA(r) ( M_PI * r * r )

int main()
{
    float r;

    printf("Enter radius of Circle\n");
    scanf("%f", &r);

    printf("Area of Circle is %f\n", AREA(r));

    return 0;
}

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 *