Can anybody please explain the behavour of C preprocessor in following examples?

允我心安 提交于 2019-12-08 08:39:25

问题


I am implementing a C macro preprocessor (C99)...

I am surprised by the following behaviour....

Ex1:

#define PASTE(x) X_##x
#define EXPAND(x) PASTE(x)
#define TABSIZE 1024
#define BUFSIZE TABSIZE

PASTE(BUFSIZE)
EXPAND(BUFSIZE)

expands to:

X_BUFFSIZE
X_1024

Ex2:

#define EXPAND(s) TO_STRING(s)
#define TO_STRING(s) #s
#define FOUR 4

TO_STRING(FOUR)
EXPAND(FOUR)

Expands to:

"FOUR"
"4"

I have gone through the "free" standard of C but I couldn’t find following things...

  1. Actually how many passes preprocessor performs?
  2. Does it replace one macro first then other and so on
  3. or does it store & replace them as #defines are encountered one by one?
  4. Whether file inclusion is done first or the macro expansion?

回答1:


You should read this page for starters. It contains gems such as:

The C standard states that, after any parameters have been replaced with their possibly-expanded arguments, the replacement list is scanned for nested macros. Further, any identifiers in the replacement list that are not expanded during this scan are never again eligible for expansion in the future, if the reason they were not expanded is that the macro in question was disabled.

I think one can infer from this that there is no fixed number of passes: each time a macro expansion happens (which generates a "replacement list"), the newly created text is scanned for further expansions. It's a recursive process.




回答2:


Actually how many passes preprocessor performs?

  1. It replaces all occurences of # PARAMETER by the stringification of that parameter
  2. It joins all tokens that have a ## inbetween
  3. it replaces all remaining ocurences of the parameters by their value
  4. It recursively expands the replacement text for occurences of other macros. (The macro itself is blocked in these recursive calls.)

Does it replace one macro first then other and so on or does it store & replace them as #defines are encountered one by one?

It replaces macros in the order it encounters them in the program text, or during the recursive replacement as described above.

Whether file inclusion is done first or the macro expansion?

first the argument of an #include is expanded if it doesn't consist in something that is either enclosed in <> or "". That then must lead to exactly that something that is in <> or in ""



来源:https://stackoverflow.com/questions/15430369/can-anybody-please-explain-the-behavour-of-c-preprocessor-in-following-examples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!