Macros in C
0 1033
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:
2 Function-like Macros: Define a snippet of code that takes arguments.
#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>Output:// 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; }
Area of the circle: 78.54In 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.
Share:




Comments
Waiting for your comments