Ida*_*dan 21 c string c-preprocessor
我正在尝试定义一个宏,假设它采用2个字符串值并返回它们之间的一个空格连接.似乎我可以使用除空间之外我想要的任何角色,例如:
#define conc(str1,str2) #str1 ## #str2
#define space_conc(str1,str2) conc(str1,-) ## #str2
space_conc(idan,oop);
Run Code Online (Sandbox Code Playgroud)
space_conc 将返回"idan-oop"
我想要一些东西回归"idan oop",建议?
fal*_*tro 48
试试这个
#define space_conc(str1,str2) #str1 " " #str2
Run Code Online (Sandbox Code Playgroud)
'##'用于连接符号,而不是字符串.字符串可以简单地并置在C中,编译器将连接它们,这就是这个宏的作用.首先将str1和str2转换为字符串(如果你像这样使用它们,请说"你好"和"世界" space_conc(hello, world))并将它们放在彼此旁边,中间是简单的单空格字符串.也就是说,由此产生的扩展将由编译器解释
"hello" " " "world"
Run Code Online (Sandbox Code Playgroud)
它将连接到哪个
"hello world"
Run Code Online (Sandbox Code Playgroud)
HTH
编辑
为了完整性,宏扩展中的'##'运算符就像这样使用,假设你有
#define dumb_macro(a,b) a ## b
Run Code Online (Sandbox Code Playgroud)
如果被称为,将导致以下结果 dumb_macro(hello, world)
helloworld
Run Code Online (Sandbox Code Playgroud)
这不是一个字符串,而是一个符号,你可能最终会得到一个未定义的符号错误,说'helloworld'不存在,除非你先定义它.这是合法的:
int helloworld;
dumb_macro(hello, world) = 3;
printf ("helloworld = %d\n", helloworld); // <-- would print 'helloworld = 3'
Run Code Online (Sandbox Code Playgroud)
#define space_conc(str1, str2) #str1 " " #str2
printf("%s", space_conc(hello, you)); // Will print "hello you"
Run Code Online (Sandbox Code Playgroud)