如何在c宏中链接加号或减号?

时间:2016-06-25 04:44:10

标签: c macros

我的代码是:

#define CHECK(x) if((x)==100)printf("%s = 100\n",#x);
#define C9(x) CHECK(x##9);CHECK(x##PLUS##9);CHECK(x##MINUS##9);
#define PLUS +
#define MINUS -

int main(){
 C9(123-45-67+8);
 return 0;
}

宏扩展到此(我添加一些\ n以使代码可读):

int main(){
 if((123-45-67+89)==100)printf("%s = 100\n","123-45-67+89");;
 if((123-45-67+8PLUS9)==100)printf("%s = 100\n","123-45-67+8PLUS9");;
 if((123-45-67+8MINUS9)==100)printf("%s = 100\n","123-45-67+8MINUS9");;;
 return 0;
}

预计会扩展到这个:

int main(){
 if((123-45-67+89)==100)printf("%s = 100\n","123-45-67+89");;
 if((123-45-67+8+9)==100)printf("%s = 100\n","123-45-67+8+9");;
 if((123-45-67+8-9)==100)printf("%s = 100\n","123-45-67+8-9");;;
 return 0;
}

怎么做? 感谢

2 个答案:

答案 0 :(得分:1)

首先,您应该在使用之前定义PLUSMINUS。其次,我认为您不希望在##PLUS周围使用MINUS

#define CHECK(x) if((x)==100)printf("%s = 100\n",#x);
#define PLUS +
#define MINUS -
#define C9(x) CHECK(x##9);CHECK(x PLUS 9);CHECK(x MINUS 9);

int main(){
 C9(123-45-67+8);
 return 0;
}

答案 1 :(得分:0)

哦,我太傻了。

此代码工作

#define C9(x) CHECK(x##9);CHECK(x+9);CHECK(x-9);

很容易= _ =