c - C 预处理器的 Null 指令有什么意义?

标签 c standards

因此,在浏览 C99 标准的 n869 草案时,我偶然发现了这一部分:

6.10.7 Null directive Semantics

A preprocessing directive of the form

# new-line

has no effect.

所以,我写了这个程序来测试它:

#
#include <stdio.h>
#

int main(void)
{
  puts("Hello, world!");

  return 0;
}

果然,gcc 对这段代码没有任何不满,即使我一路发出警告等。我意识到该语言中还有一些其他结构并不明显,例如初始化程序、枚举 def 等中允许的额外逗号,但这是有目的的(例如简化代码生成器的编写)。

但是,我看不出这个有什么用。谁能想出一个合理的用例/理由来拥有它?

最佳答案

来自 GCC 文档,第 1.7 节:

The null directive consists of a #' followed by a Newline, with only whitespace (including comments) in between. A null directive is understood as a preprocessing directive but has no effect on the preprocessor output. The primary significance of the existence of the null directive is that an input line consisting of just a#' will produce no output, rather than a line of output containing just a `#'. Supposedly some old C programs contain such lines.

请记住,C 预处理器本身就是一个程序,它有输入和输出。 C 预处理器的输出通常包括 程序注释,但如果注释出现在以“#”符号开头的行中,并且除了空格和注释外没有其他内容,则注释不会出现在预处理器输出中。因此 null 指令导致内容出现在源代码中,但不出现在预处理器输出中。

例子:

预处理器将转换

#include <stdio.h>
#define HELLO 1
# /*This comment is for preprocessor only*/
HELLO
/*This comment is for preprocessed code*/

进入

(... preprocessed contents of stdio.h ...)
1
/*This comment is for preprocessed code*/   

关于c - C 预处理器的 Null 指令有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10020922/

相关文章:

c - 为什么数组不打印正确的数字?

c - 为什么 math.h 不定义倒数三角函数?

c# - 通过导入将 XSD 转换为 XML

c - 为什么这段代码会出现编译错误?

c - MPI 子数组发送错误

c - 使用字符串格式化程序导致未处理的异常出现 "Access violation writing location"

c - C 函数中的段错误

standards - “dead code”和 “unreachable code”有什么区别?

C - 标准库中函数的源代码

c++ - 什么都不捕获的 lambda 可以访问全局变量吗?