Macros in C
×


Macros in C

195

 Macros in C are used to define constants or inline code snippets that can be expanded inline during preprocessing.

They provide a way to simplify code and make it more readable and maintainable.

Syntax of Macros in C:

#define MACRO_NAME value
#define FUNCTION_MACRO(arg) (expression)

Types of Macros

1Object-like Macros:

Define a constant value or expression.


2 Function-like Macros:

Define a snippet of code that takes arguments.

#define SQUARE(x) ((x) * (x))

Example:

#include<stdio.h>

// Object-like Macro
#define PI 3.14159

// Function-like Macro
#define SQUARE(x) ((x) * (x))

int main() {
    int radius = 5;
    
    // Calculate area using PI macro
    float area = PI * SQUARE(radius);
    
    printf("Area of the circle: %.2f\n", area);
    
    return 0;
}
Output:

Area of the circle: 78.54

In this example:

 PI is an object-like macro defining the value of pi.

 SQUARE(x) is a function-like macro that squares its argument.

 We use these macros to calculate the area of a circle based on its radius.

 Macros help reduce code redundancy and improve code maintainability by allowing you to define reusable constants and code snippets.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments