切断预处理线

标签 c macros newline

在 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/

相关文章:

macros - CL 样式宏中的多个(定义)

PHP 表单去除换行符

code jam练习--阅读题

c - C语言读取文件时如何将不同的列放入不同的数组中

java - Apache Velocity 宏生成 Base64 编码的字符串

C++ 编译时类型注册技巧

php - 使用 PHP DOMDocument() 类时保留新行

python - 为什么多行字符串在打印或写入时会发生变化? (Windows 上的 Python 3.6)

c - 如何将 Go 字符串数组转换为 C 字符串数组?

c - stdarg.h中定义的函数va_start(va_list ap,parmN),为什么标识符parmN不能用寄存器存储类声明?