Categories
a. Preprocessor & Macros

Function like Macros

You can also define macros that work in a similar way like a function call. This is known as function-like macros. For example,

#define circleArea(r) (3.1415*(r)*(r))

Every time the program encounters circleArea(argument), it is replaced by (3.1415*(argument)*(argument)).

Suppose, we passed 5 as an argument then, it expands as below:

circleArea(5) expands to (3.1415*5*5)

Example 2: Using #define preprocessor

#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)

int main() {
    float radius, area;

    printf("Enter the radius: ");
    scanf("%f", &radius);
    area = circleArea(radius);
    printf("Area = %.2f", area);

    return 0;
}

Leave a Reply

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