C Programming Tutorial

C Programming Tutorial

#define in C

#define in C is a preprocessor directive that is used to define a constant or a macro. When the preprocessor encounters #define, it replaces all occurrences of the defined identifier in the code with its corresponding value or definition. This is done before the code is compiled, so it can help simplify and optimize the code.

Here’s an example:

#define MAX_VALUE 100

int main() {
    int arr[MAX_VALUE];
    // Code that uses the array
    return 0;
}

In this example, #define is used to define a constant MAX_VALUE with a value of 100. When the preprocessor encounters MAX_VALUE in the code, it replaces it with the value 100.

#define can also be used to define macros, which are code snippets that can be used to simplify or abstract complex code. For example:

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

int main() {
    int a = 5;
    int b = SQUARE(a); // b = ((a) * (a)) = 25
    return 0;
}

In this example, #define is used to define a macro SQUARE(x) that calculates the square of a number. When the preprocessor encounters SQUARE(a) in the code, it replaces it with ((a) * (a)), which calculates the square of a.

C program that uses #define to define a constant:

#include <stdio.h>
#define PI 3.14159

int main() {
    double radius, area;

    printf("Enter the radius of the circle: ");
    scanf("%lf", &radius);

    area = PI * radius * radius;

    printf("The area of the circle is %lf\\n", area);

    return 0;
}

In this program, #define is used to define the constant PI with a value of 3.14159. When the preprocessor encounters PI in the code, it replaces it with the value 3.14159.

The program prompts the user to enter the radius of a circle, and calculates the area using the formula area = PI * radius * radius. The calculated area is then displayed on the screen.

Note that #define is used before the main() function, because it is a preprocessor directive that is processed before the code is compiled.

Share This Article