0
0
Cprogramming~5 mins

Define macro

Choose your learning style9 modes available
Introduction

Define macros let you give a name to a value or code snippet. This makes your code easier to read and change.

You want to give a name to a number or text used many times.
You want to create a shortcut for a piece of code you use often.
You want to make your program easier to update by changing one place.
You want to avoid repeating the same value or code in many places.
Syntax
C
#define NAME value_or_code

Macros are replaced by the preprocessor before the program runs.

Macros do not use memory like variables.

Examples
This defines PI as 3.14 everywhere in the code.
C
#define PI 3.14
This defines a macro to find the maximum of two values.
C
#define MAX(a,b) ((a) > (b) ? (a) : (b))
This defines a text macro for a greeting message.
C
#define GREETING "Hello, friend!"
Sample Program

This program uses macros to define PI and a formula to calculate the area of a circle. It then prints the area for radius 5.0.

C
#include <stdio.h>

#define PI 3.14
#define AREA_OF_CIRCLE(r) (PI * (r) * (r))

int main() {
    double radius = 5.0;
    double area = AREA_OF_CIRCLE(radius);
    printf("Area of circle with radius %.1f is %.2f\n", radius, area);
    return 0;
}
OutputSuccess
Important Notes

Macros are simple text replacements done before the program runs.

Be careful with parentheses in macros to avoid unexpected results.

Macros do not have types like variables do.

Summary

Define macros give names to values or code snippets.

They help make code easier to read and update.

Macros are replaced before the program runs, so they do not use memory.