#define vs #undef in C language
In this article, we will discuss the difference between #define and #undef pre-processor in C language.
What are Pre-Processor Directives?
- Pre-processor is a program that performs before the compilation.
- It only notices the # started statement.
- # is called preprocessor directive.
- Each preprocessing directive must be on its own line.
- The word after # is called the preprocessor command.
#define
The #define directive defines an identifier and a character sequence (a set of characters) that will be substituted for the identifier each time it is encountered in the source file.
Syntax
#define macro-name char-sequence
The identifier is referred to as a macro name and the replacement process is called macro expansion.
For example,
#define PI 3.14
Here, PI is the macro name and 3.14 is the char-sequence.
Examples of #define Directive
Example 1: Below is the C program illustrating the use of #define.
C
#include <stdio.h>
#define PI 3.14
int main()
{
int r = 4;
float a;
a = PI * r * r;
printf ( "area of circle is %f" , a);
return 0;
}
|
Output
area of circle is 50.240002
Explanation
- In this example, PI is the macro-name and the char-sequence is 3.14.
- When the program runs the compiler will check the #define command first and assign the PI as 3.14.
- Now in the entire program wherever the compiler sees the PI word it will replace it with 3.14.
Example 2: Below is the C program printing product of two numbers using #define.
C
#include <stdio.h>
#define PRODUCT(a, b) a* b
int main()
{
printf ( "product of a and b is %d" , PRODUCT(3, 4));
return 0;
}
|
Output
product of a and b is 12
Explanation
- In this example, a macro-name as the product is defined and passes two arguments as a and b and gives the char-sequence as the product of these two arguments.
- When the compiler sees the macro-name in the print statement, it replaces the macro-name with the product of a and b and gives the answer as their product.
#undef
The #undef preprocessor directive is used to undefine macros.
Syntax
#undef macro-name
Example of #undef Directive
Below is the C program to illustrate the use of #undef in a program.
C
#include <stdio.h>
#define PI 3.14
#undef PI
int main()
{
int r = 6;
float a;
a = PI * r * r;
printf ( "area of circle is %f" , a);
return 0;
}
|
Output
Explanation
In this example, when #undef is used, it will remove the definition of the macro specified by #define. As a result, the macro will become undefined, and if the program tries to use the undefined macro, the compiler will show an error.
Last Updated :
22 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...