Open In App

#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?

#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 program illustrating the use of
// #define
 
#include <stdio.h>
 
// Defining a constant value for PI using #define
#define PI 3.14
 
// Driver Code
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

Example 2: Below is the C program printing product of two numbers using #define.




// C program to find the product of
// two numbers using #define
 
#include <stdio.h>
 
// Define a macro using #define to calculate the product of
// two numbers
#define PRODUCT(a, b) a* b
 
// Driver Code
int main()
{
    // Print the product of 3 and 4 using the PRODUCT macro
    printf("product of a and b is %d", PRODUCT(3, 4));
 
    return 0;
}

Output
product of a and b is 12

Explanation

#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 program to illustrate the use
// of #undef in a program
 
#include <stdio.h>
 
// Define the constant value for PI
#define PI 3.14
 
// Undefine the previously defined PI
#undef PI
 
// Driver Code
int main()
{
    int r = 6;
    float a;
 
    // Since PI is undefined, this calculation will result
    // in a compilation error
    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.


Article Tags :