Nesting of macro & undefine a macro



If we use one define a macro in another define a macro that is called nested macro. As we can see here in the example:-  

#define M 100    // define macro  

#define N M+10 // nesting macro  

 

If we need to redefine the macro we will undefine the first macro and again we will define the second macro. To undefine a macro we will use the #undef identifier (by which name you have defined a macro) keywordWe don’t need to use a semicolon at the end. Let's undefine above define a macro,  

#undef M // undefining the macro 

 

 

While Undefining argument macro, we can write #undef identifier. Let's see in the example:-  

 

#deinfe CUBE (a) a*a*a 

#undef CUBE  // while undefining the argument macro we can write only identifier.  

 

QUESTION:- How to use nesting of macro with the argument in the program.  



#include <stdio.h>
#include <conio.h>
#define SQUARE(x) ((x) * (x))     // 5*5 = 25
#define CUBE(x) (SQUARE(x) * (x)) // 25*5 = 125
void main()
{
    int result;
    result = CUBE(5);
    printf("The result is %d"result);
#undef CUBE // we don't Wanna a use CUBE macro from here
    getch();
}

output  

The result is 125 

 

QUESTION: - write a c program to take a user input and replace user input in define macro and after the execution of program undefine the macro. 


#include <stdio.h>
#define ADD(ab) (a + b)
#define ADDS(cd) (c + d)
void main()
{
    int abcdsum;
    printf("enter a value of a: ");
    scanf("%d", &a);
    printf("enter a value of b: ");
    scanf("%d", &b);
    printf("enter a value of c: ");
    scanf("%d", &c);
    printf("enter a value of d: ");
    scanf("%d", &d);
    sum = ADD(ab) - ADDS(cd);
    printf("the sum is %d"sum);
#undef ADDS
}

output  

enter a value of a: 4 

enter a value of b: 5 

enter a value of c: 2  

enter a value of d: 3 

the sum is 4 

 

NOTE:- if we don’t want to use macro after the program executes then we will undefine a macro as we did in the program.  

Follow our page for regular updates.

0 Comments