字符串化C中的运算符不能在linux上运行

时间:2015-09-30 12:15:54

标签: c operators c-preprocessor

我有以下代码在Windows中按预期工作但在Ubuntu上我收到错误" toString1未在此范围内声明"。

#include <stdio.h>
#define a                    2
#define b                    3
#define c                    4
#define d                    5
#define toString1(S)         #S
#define toString(S)          toString1(S)
#define numbers              a,b,c,d
#define numbersS             toString(numbers)
int main()
{
 int a1 = 0, a2 = 0, a3 = 0, a4 = 0;
 if (sscanf_s(numbersS, "%d,%d,%d,%d", &a1, &a2, &a3, &a4) == 4)
 { 
    printf("The numbers were assigned correctly");
 }
 printf("%d %d %d %d ", a1, a2, a3, a4);
}

可能是什么原因?如果我删除toString1并生成

#define toString(S)           #S

对于Windows和Ubuntu上的每个变量,结果为0。

有人可以对此作出解释吗?

1 个答案:

答案 0 :(得分:1)

编译器说:

 error: macro "toString1" passed 4 arguments, but takes just 1

 sscanf(numbersS, "%d,%d,%d,%d",a1,a2,a3,a4); 

的确,numbersStoString(numbers),数字为is a,b,c,d

所以你需要一些变量宏魔法才能正常工作:

#define a                    2
#define b                    3
#define c                    4
#define d                    5
#define toString1(S...)         #S
#define toString(S...)          toString1(S, __VA_ARGS__) 
#define numbers              a,b,c,d
#define numbersS             toString(numbers)

int main()
{
    int a1,a2,a3,a4;
    sscanf(numbersS, "%d,%d,%d,%d",&a1,&a2,&a3,&a4); 
    printf("%d %d %d %d", a1,a2,a3,a4);

}

在线:https://ideone.com/puPd6x

(另请注意,我已修复sscanf以获取地址)