gpt4 book ai didi

c - 抑制 C 宏变量替换

转载 作者:太空狗 更新时间:2023-10-29 17:05:13 24 4
gpt4 key购买 nike

我有这段代码(实际上是垃圾收集 Forth 系统的解释器的一部分):

#define PRIMITIVE(name) \
do \
{ \
VocabEntry* entry = (VocabEntry*)gc_alloc(sizeof(VocabEntry)); \
entry->code = name; \
entry->name = cstr_to_pstr(#name); \
entry->prev = latest_vocab_entry; \
latest_vocab_entry = entry; \
} \
while (false)

PRIMITIVE(dup);
PRIMITIVE(drop);
PRIMITIVE(swap);
// and a lot more

但是有一个问题:在行中

entry->name = cstr_to_pstr(#name);

name 字段被替换为 dupdropswap 和其他字段。我希望字段名称不被替换。

那么,除了简单地重命名宏参数之外,还有什么办法可以解决这个问题吗?

对于一个答案,请解释一般情况下是否有一种方法可以禁止在宏主体中替换宏参数名称。不要回答“就这样做吧”(请)。

最佳答案

你可以定义一个不同的宏来扩展到name,像这样:

#define Name name

并更改 PRIMITIVE 宏中的 name 字段以使用新宏,如下所示:

#define PRIMITIVE(name) \
do \
{ \
VocabEntry* entry = (VocabEntry*)gc_alloc(sizeof(VocabEntry)); \
entry->code = name; \
entry->Name = cstr_to_pstr(#name); \
entry->prev = latest_vocab_entry; \
latest_vocab_entry = entry; \
} \
while (false)

除了在宏体中使用与参数名称不同的名称或更改参数名称外,在 C 语言中没有其他方法可以做到这一点。根据 C 2011 (N1570) 6.10.3.1 1,当识别出类似函数的宏时,将立即替换参数名称,除非出现 ###,并且有没有其他异常(exception):

After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded.

# 标记将参数名称更改为字符串,在这种情况下没有用。 ## 标记扩展参数名称并将其与相邻标记粘贴在一起,在这种情况下也没有用。

关于c - 抑制 C 宏变量替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com