为什么有时宏扩展会增加空间? [英] Why does macro expansion add a space sometimes?

查看:47
本文介绍了为什么有时宏扩展会增加空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

#define F a
F/

它扩展为 a/ godbolt

It expands to a/ godbolt

如果我这样做:

#define F /
F/

它扩展为//,并在 goodbolt

It expands to / / with a space in between goodbolt

但是,如果我将其转换为字符串并打印,它不会添加任何空格 goodbolt :

But if I convert it to a string, and print it, it doesn't add any spaces goodbolt:

#include <stdio.h>

#define STR_IMPL(x) #x
#define STR(x) STR_IMPL(x)

#define F /


int main() {
  puts(STR(F/));
}

为什么之间只有一个时间间隔?在其他情况下是否可以添加更多空间?

Why is there a space in between, but only some of the time? Is it allowed to add more spaces in other cases?

推荐答案

语言规范大致是这样的:

The language specification is like this, at a high level:

  • 将输入分为一系列令牌.
  • 在该令牌序列上运行预处理器(导致另一个令牌序列)
  • 编译生成的令牌序列.

步骤之间没有任何中间纯文本表示形式的规范.您在预处理器输出"中看到的是只要整个翻译过程的最终结果都按规定行事,这完全取决于供应商的想法.

There is no specification of any intermediate plain-text representation between the steps . What you are seeing in the "preprocessor output" is entirely at the whim of the vendor, so long as the final result of the whole translation process behaves as specified.

使用 #define F/ STR(F/)的示例进行分析:

Analysis of the example with #define F / and STR(F/) :

首先请注意, #define F/后跟换行符表示 F 被两个标记 w /代替code>(我在其中使用 w 表示空白标记).

First note that #define F / followed by newline means that F is replaced by the two tokens w / (where I am using w to mean a whitespace token).

令牌化后 STR(F/)的预处理令牌的顺序为:

The sequence of preprocessing tokens for STR(F/) after tokenization is:

  • STR ( F /)

在第一轮宏替换之后,标记为:

After the first round of macro substitution the tokens are:

  • w STR_IMPL ( w //)
  • w, STR_IMPL, (, w, /, /, )

第二轮之后,令牌为:

  • w "/"//" .

#预处理运算符的定义包括删除了前导空格.因此令牌序列 w //变为"///" ,而不是";//" .

The definition of the # preprocessing operator includes that leading whitespace is removed. So the token sequence w, /, / becomes "//", not " //".

F/或两个斜杠之间在任何地方都没有空格.

There was never any space between the F/ or the two slashes at any point.

这篇关于为什么有时宏扩展会增加空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆