What is #undef Directive in C Programs?

Question: What is #undef Directive and What is this used for in C Programs?

Answer: #undef directive undefines a previously defined #define. For example,

#define LIMIT 100
 
#undef LIMIT

Preprocessor undefines LIMIT by removing its definition. Even if we haven’t defined LIMIT, for ex.,

#define LIMIT

It’s possible to undefine it.

#undef LIMIT

Notice further that even if we are not sure a given symbol is defined or not, we can undefine it to be on the safe side before using it.

advertisement
advertisement

A few predefined macros like __DATE__, __FILE__, __TIME__ etc. can’t be undefined.

Let’s Consider the fragment of code below,

#define MAX(a, b)        ((a) > (b)) ? (a) : (b)

Now let’s use this in a program,

int main(void)
{
    printf("Larger of %d, %d is %d\n", a, b, MAX(a, b));
    return 0;
}

If we want to redefine the MAX(a, b), we have to remove its prior definition. This we can do with #undef as follows,

/* #undef un-#define's MAX(a, b) by removing its definition */
#undef MAX(a, b)

/* then redefine MAX(a, b) */
#define MAX(a, b) \
if ((a) > (b)) \
printf(“%d\n”, (a)); \
else \
printf(“%d\n”, (b));

Notice here that when a macro definition is long enough not to fit in one line, break it over several lines, ending each line except the last with back slash ‘\’.

advertisement

And now use the new definition of MAX(a,b),

int main(void)
{
    printf("Larger of %d, %d is %d\n", a, b, MAX(a, b));
}

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.