Loading...
Loading...
00:00:00

What Is Macros And Preprocessor Directive In C?

In C language, a macro is a preprocessor directive that allows developers to define constants, functions, or code snippets that can be reused throughout a program. Macros are defined using the #define keyword and are usually used for code optimization, as they can be used to reduce the amount of redundant code and make the code more readable.

For example, consider the following macro:

#define MAX(x, y) ((x) > (y) ? (x) : (y))

This macro defines a function called MAX that takes two parameters x and y and returns the maximum value of the two. This macro can be used anywhere in the program to find the maximum value of two numbers.

On the other hand, a preprocessor directive is a special command that is processed by the preprocessor before the actual code is compiled. The preprocessor is a part of the compiler that processes the source code before it is compiled into machine code. Preprocessor directives are usually used to include header files, define constants, and perform other preprocessing tasks.

Some examples of preprocessor directives in C language are:

#define: Used to define macros and constants.

#include: Used to include header files.

#ifdef and #ifndef: Used for conditional compilation.

#pragma: Used to provide hints or instructions to the compiler.

In summary, macros are used to define constants and functions that can be reused in the program, while preprocessor directives are used to perform various preprocessing tasks like including header files and defining constants.

Macro is simple definition of value that is replaced by compiler while compling. Macro is name of value and it is declare at the top of C program. While compiling c program by Compiler, it replace the actual value with Macro. A Macro may be Predefined or User-defined. For Creating a Macro we have to use #define before the macro value. #define is known as preprocessor directive.

Example of Macro Create a Macro for replace actual value

#include <stdio.h>
#include <stdlib.h>
#define Total 500                          // define a macro  integer
#define PI 3.14                            // define a macro  float
#define WEBSITE "www.PanditProgrammer.com" // define a macro value string

int main(int argc, char const *argv[])
{
    printf("The value of Total macro is %d\n", Total);     // macro Total
    printf("the value of PI is %f\n", PI);                 // macro PI
    printf("This is programming webiste - %s\n", WEBSITE); //macro WEBSITE
    return 0;
}