#define in C
×


#define in C

218

 The #define directive in C is used to define macros, which can be either constants or code snippets.

 Macros defined with #define are processed by the preprocessor before compilation, allowing for code simplification and readability.

syntax of #define in C

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

Examples:

Object-like Macro - Defining a constant:

#define PI 3.14159

Function-like Macro - Defining a code snippet:

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

Uses of #define in C:

Constants: Simplify code by replacing magic numbers with named constants.

Code Snippets: Define reusable snippets of code or computations.

Example:

#include<stdio.h>

// Object-like Macro: defining a constant
#define PI 3.14159

// Function-like Macro: defining a code snippet
#define SQUARE(x) ((x) * (x))

int main() {
    int radius = 5;
    int side = 10;
    
    // Using the PI macro to calculate the circumference
    float circumference = 2 * PI * radius;
    
    // Using the SQUARE macro to calculate the area
    int area = SQUARE(side);
    
    printf("Circumference of the circle: %.2f\n", circumference);
    printf("Area of the square: %d\n", area);
    
    return 0;
}

Output:

Circumference of the circle: 31.42
Area of the square: 100


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