What is macro override in C? What's the point, given so many restrictions on it?

I first came across the concept of "overriding macro" while reading a book by Mike C Banahanom (Section 7.3.2) . But from what I can measure from the paragraph below, overriding would be nothing more than repeating the same thing given the tight constraints. Of course my understanding is wrong and the author must make sense. So you can just explain what exactly the macro overrides in C, and what exactly we can do to override it after we follow the restrictions and rules given to do so. Sample code will be very helpful. Thank.

The extracted text follows:

The standard allows any macro type to be overridden at any time using a different #define, provided that there is no attempt to change the macro type and that the tokens constituting both the original definition and the override are identical in number, ordering, spelling and use of spaces. In this context, all white space is considered equal, so this would be correct:

#define XXX abc/*comment*/def hij
#define XXX abc def hij 


because comment is a form of space. The character sequence for both cases (ws stands for white space token):

# w-s define w-s XXX w-s abc w-s def w-s hij w-s



source to share

1 answer

In practice, you don't want to override macros at all. In most cases, this is due to a name clash (two pieces of code defining a macro with the same name, which may or may not do the same). The rule you cite says that overrides are allowed in the case where the only difference between the two definitions is a space. In this case, both definitions will do the same. In any other case, all bets are disabled.

For example, a common thing is a maximum of two numbers. If you are writing a MAX macro, one way to do it:

// ASSUME: multiple references to macro parameters do not cause problems
#define MAX(a, b) ((a) > (b) ? (a) : (b))


Since MAX

is the obvious name for a macro that returns a maximum of two numbers, there is a pretty good chance that someone else might have the same idea as well as define the macro MAX

. If they define it exactly like you do, the compiler will accept multiple definitions because they do the same (although some compilers will warn about this).

If someone defines MAX

otherwise, the compiler will throw an error when overridden. Throwing a mistake is good. If the compiler always chose either the first or the last definition, the programmer most likely will not know that a different macro will be used than they expected.

If you need to work around some macro definitions (for example, two different third-party libraries choose the same name), you can use #ifdef

to check if the macro has already been determined, and #undef

- "undefine" the first definition, if you prefer the second. Such solutions are usually fragile. Once you have a choice, it's best to avoid name collisions.



All Articles