Domanda

In many of the C and C++ files I have seen macros like this:

#ifdef X
#undef X  // no statements in between
#endif

I feel that, it's adequate to simply write:

#undef X

If the macro X wasn't defined, then the #undef should have no effect.

Is it ok to put standalone #undef, if I want to only undefine a macro ? Does that make the coding practice bad in anyway ?

È stato utile?

Soluzione

See ISO C99 6.10.3.5 paragraph 2.

A preprocessing directive of the form

# undef identifier new-line

causes the specified identifier no longer to be defined as a macro name. It is ignored if the specified identifier is not currently defined as a macro name.

Even Visual C++ 6 (which was notorious for bad standards compliance) allows this:

You can also apply the #undef directive to an identifier that has no previous definition. This ensures that the identifier is undefined. Macro replacement is not performed within #undef statements.

Altri suggerimenti

I'm sure it's an artifact of history. As mentioned in jdigital's answer, the 2nd edition of K&R says

It is not erroneous to apply #undef to an unknown identifier.

However, that sentence is not in the 1978 edition. I'm pretty sure pre-standard compilers would often throw an error if you tried to #undef an undefined macro.

Also, the ANSI C Rationale says:

It is explicitly permitted to #undef a macro that has no current definition.

I'd imagine that if it was already universal practice, there would be no need to call it out in the rationale.

All that said, it's not necessary in modern code, but it doesn't really hurt either.

Kernighan and Ritchie (2nd edition) agree with you.

EDIT: quote from the source (section A12.3):

A control line of the form

# undef identifier

causes the identifier's preprocessor definition to be forgotten. If is not erroneous to apply #undef to an unknown identifier.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top