在 C 中,预处理器语句可以使用 \
字符扩展到多行。
#define SWAP(a, b) { \
a ^= b; \
b ^= a; \
a ^= b; \
}
这会将宏分散到多行,但是有没有办法在行尾之前切断宏?即:我想在宏的同一行上编写代码,但不希望它成为宏的一部分。例如,有没有办法使以下成为可能?
#include <stdio.h> (some character here to end macro) int main(int argc, const char **argv) { return 0; }
有没有办法合法地将预处理器语句和 main
函数(或任何其他代码)放在同一行?
最佳答案
不,不适用于 #include
您在问题中特别提到的陈述。而且,尽管我没有专门检查(a),所有 预处理指令可能都是这种情况。
标准规定换行符是语法的组成部分(来自 C11 6.10.2 Source file inclusion
):
A preprocessing directive of the form
# include <h-char-sequence>
new-line
...
您可以在 #include
之后发表评论指令,因为用单个空格替换注释发生在第 3 阶段,而预处理指令在第 4 阶段处理(参见 C11 5.1.1.2 Translation phases
)。
但这并不能帮助您尝试放置非评论,例如 main()
函数定义在同一行,这仍然是一个禁忌。
但我要问你的问题是:为什么你会想要这样做?简单输出两行就搞定了。这不像我们正在遭受世界范围内的换行符短缺:-)
(a) Jonathan Leffler 检查过,所以这个陈述几乎可以肯定是正确的。
来自 ISO/IEC 9899:2011,§6.10 预处理指令:
# if
constant-expression new-line groupopt
# ifdef
identifier new-line groupopt
# ifndef
identifier new-line groupopt
# elif
constant-expression new-line groupopt
# else
new-line groupopt
# endif
new-line
# include
pp-tokens new-line
# define
identifier replacement-list new-line
# define
identifier lparen identifier-listopt ) replacement-list new-line
# define
identifier lparen ... ) replacement-list new-line
# define
identifier lparen identifier-list , ... ) replacement-list new-line
# undef
identifier new-line
# line
pp-tokens new-line
# error
pp-tokensopt new-line
# pragma
pp-tokensopt new-line
#
new-line
关于切断预处理线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23379901/