What is #undef Directive and Why this is Used For 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.,

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

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,

advertisement
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 ‘\’.

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

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

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

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

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!
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn