[英]How to use ## in a macro?
Here is a simple demo. 这是一个简单的演示。 But Xcode shows me the error 'pasting formed '->client_port', an invalid preprocessing token expanded from macro 'PARSE_COLUMN' cfg->##column = value'
但是Xcode向我显示了错误“粘贴形成的'-> client_port',这是从宏'PARSE_COLUMN'cfg-> ## column = value'扩展而来的无效预处理令牌。
I just want to set value for my struct quickly, and what is the problem with 'cfg->##column = value' 我只想快速为我的结构设置值,“ cfg-> ## column = value”有什么问题?
#include <stdio.h>
#define PARSE_COLUMN( column, value ) \
printf("parse column:%s\n",#column);\
cfg->##column = value
typedef struct {
int client_port;
} server_config;
int main(void) {
server_config *cfg = new server_config;
PARSE_COLUMN(client_port,123);
return 0;
}
##
is used to concatenate two macro arguments, for example column##value
would be exchanged with client_port123
in the code above. ##
用于连接两个宏参数,例如,在上面的代码中column##value
将与client_port123
交换。
You don't need to use it here, you can just write cfg->column = value
. 您无需在这里使用它,只需编写
cfg->column = value
。
##
is used to concatenate two valid pre-processor tokens into a single one. ##
用于将两个有效的预处理器令牌连接为一个令牌。 cfg->
is not a valid pre-processor token, but rather cfg
. cfg->
不是有效的预处理器令牌,而是cfg
。 Therefore you get a compiler error. 因此,您会收到一个编译器错误。
In this case you can simply drop the ##
and it will work: cfg->column = value
. 在这种情况下,您只需删除
##
即可: cfg->column = value
。
Please note that macros like these are usually bad practice and functions are preferable. 请注意,此类宏通常是不好的做法,最好使用函数。
## is used to split tokens, then concatenate them. ##用于拆分令牌,然后将其串联。
Example: 例:
#define A1(name, type) type name_##type##_type
#define A2(name, type) type name##_##type##_type
A1(a1, int); /* int name_int_type; */
A2(a1, int); /* int a1_int_type; */
In macro A1, name_##type##_type is split into 3 parts: { name_ , type , _type }, only part 2 type is a valid argument and can be replaced. 在宏A1中,name _ ## type ## _ type分为3部分:{ name_ , type , _type },只有第2部分type是有效参数,可以替换。
In macro A2, name##_##type##_type is split into 4 parts: { name , _ , type , _type }, both part 1 name and part 3 type are valid arguments and can be replaced. 在宏A2中,name ## _ ## type ## _ type分为4个部分:{ name , _ , type , _type },第1部分的name和第3部分的type都是有效的参数,可以替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.