Unrivaled Macro Bracket

What is the correct output for preprocessing the next three lines according to C99 rules?

#define y(x) x #define x(a) y(a x(1) x(2))) 

BTW cpp under linux gives an error message, but I don’t understand why the answer is not easy

 1 2 

Assuming cpp is correct, and I'm wrong, I would really appreciate an explanation.

+4
source share
2 answers

When a macro is found, the preprocessor collects the arguments into a macro and then scans each macro in isolation for the other macros to expand it in the argument BEFORE the first macro extension:

6.10.3.1 Substitution of the argument

After the arguments have been defined to invoke a functionally similar macro, the argument is replaced. A parameter in the substitution list, if it is not specified using the preprocessing token # or ## or the preprocessing token ## (see below), is replaced with the corresponding argument after all the macros contained in it have been expanded. Before replacing, each argument preprocessing token was completely replaced by the macro, as if they formed the rest of the preprocessing file; no other pre-processing tokens are available.

So, in this particular example, he sees x(1) and extends this by providing

 y(1 x(2))) 

He then identifies the macro message y(1 x(2)) , with the argument 1 x(2) and prescans, which is for macros to expand. In this case, it finds x(2) , which expands to y(2 , and then raises an error due to missing ) for the macro y . Note that at the moment he is still trying to expand the argument of the first macro y , so he looks at it in isolation, not considering the rest of the input file, unlike the extension that takes place for 6.10.3.4

Now the question is whether this is really a mistake, or if the preprocessor should process this sequence y(2 as not being a macro call at all, since there is no ")". If it is the last one, then it will extend this call y by 1 y(2 , which will then be merged with the rest of the input ( ) ) and will eventually expand to 1 2

+6
source

After the macro has been expanded, attempts to expand the macros in the resulting text will be isolated before they are combined with the surrounding text. Thus, trying to expand y(1 gives this error. It would actually be very difficult to specify a macro decomposition that works the way you want, but at the same time satisfying many other required types of behavior (for example, the lack of infinite recursion).

0
source

Source: https://habr.com/ru/post/1379211/


All Articles