问题
Honestly I know the syntax of the C programming language well, but know almost nothing about the syntax of the C preprocessor, although I use it in my programming practice sometimes.
So the question. Suppose we have a simple macro that expands to nothing:
#define macro(param)
What is the restrictions for the syntax that can be put inside macro invoking construction?
It is certainly impossible to use single or multiple comma when invoking the macro:
macro(,); // won't compile
However if we put the comma into the brackets it will be accepted by C preprocessor:
macro((,)); // compiles fine
Of course, you can't use the comment characters:
macro(//); // compile error
because, as far as I know, comments are processed by preprocessor itself.
Unclosed quotes and round brackets aren't allowed too when using the macro:
macro("); // compile error
But characters unused in the C syntax are accepted well:
macro(@#$); // compiles
Even characters of foreign languages work fine:
macro(бла-бла-бла я пишу по-русски); // compiles too
Can I use a random valid C/C++ code in curly brackets when invoking the macro? Can I use a random valid C/C++ code without curly brackets? The following code seems to compile fine:
macro(int a = 5; printf("%d\n", a););
回答1:
You cannot pass arbitrary text to be ignored with your proposed scheme:
The C preprocessor will read the input file and parse it as a sequence of preprocessing tokens, after stripping comments, to pass to the macro as arguments. It matches parentheses to determine what tokens constitute arguments separated by
,
.Text containing strings or character constants with unrecognized escape sequences or stand alone backslashes does not parse as standard preprocessing token. Whether
macro(@#$);
compiles is implementation dependent.Note however that you can work around the
,
problem by defining your macro as taking a variable number of arguments:#define macro(...)
来源:https://stackoverflow.com/questions/48844577/what-type-of-content-is-allowed-to-be-used-as-arguments-for-c-preprocessor-macro