C #define

#define in C


he C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program before it is compiled. These transformations can be the inclusion of header file, macro expansions etc.

All preprocessing directives begin with a # symbol. For example,

#define PI 3.14

Some of the common uses of C preprocessor are:


Including Header Files: #include

The #include preprocessor is used to include header files to C programs. For example,

#include 

Here, stdio.h is a header file. The #include preprocessor directive replaces the above line with the contents of stdio.h header file.

That's the reason why you need to use #include  before you can use functions like scanf() and printf().

You can also create your own header file containing function declaration and include it in your program using this preprocessor directive.

#include "my_header.h"

Visit this page to learn more about using header files.


Macros using #define

A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive.

Here's an example.

#define c 299792458  // speed of light

Here, when we use c in our program, it is replaced with 299792458.


Example 1: #define preprocessor

#include 
#define PI 3.1415

int main()
{
    float radius, area;
    printf("Enter the radius: ");
    scanf("%f", &radius);

    // Notice, the use of PI
    area = PI*radius*radius;

    printf("Area=%.2f",area);
    return 0;
}

Function like Macros

You can also define macros that work in a similar way like a function call. This is known as function-like macros. For example,

#define circleArea(r) (3.1415*(r)*(r))

Every time the program encounters circleArea(argument), it is replaced by (3.1415*(argument)*(argument)).