宏将运算符作为参数

时间:2016-06-06 21:20:27

标签: c c-preprocessor

我正在研究C中的项目,我想知道我们是否可以这样做:

#define OPERATION(operator) 1 (operator) 3

并像那样使用

// Some code (those are exemples)
a = OPERATION(+);
a = OPERATION(==);
// Some more code

感谢您的回答

我正在编写的代码,尝试改进此代码以对矩阵执行操作。我还在努力。将来,我打算在外面使用Duff的设备。

#define MATRIX_OPERATION(ans,a,b,width,height,eqOp,op)   int y, n, orig = ((height) + 9) / 10, swControl = (height)%10; \
 for(int x=0; x<(width); x++){ \
 y = 0; \
 n = orig; \
 switch (swControl){ \
    case 0: do { (ans) (eqOp) (b) (op) (a); \
    case 9: (ans) (eqOp) (b) (op) (a); \
    case 8: (ans) (eqOp) (b) (op) (a); \
    case 7: (ans) (eqOp) (b) (op) (a); \
    case 6: (ans) (eqOp) (b) (op) (a); \
    case 5: (ans) (eqOp) (b) (op) (a); \
    case 4: (ans) (eqOp) (b) (op) (a); \
    case 3: (ans) (eqOp) (b) (op) (a); \
    case 2: (ans) (eqOp) (b) (op) (a); \
    case 1: (ans) (eqOp) (b) (op) (a); \
        } while (--n); \
}}

2 个答案:

答案 0 :(得分:0)

是的,你可以,几乎完全像你的尝试:

#define OPERATION(operator) 1 operator 3

答案 1 :(得分:0)

它可以工作,但事情是为什么让你的代码复杂,例如你可以轻松做1 + 3而不是使用宏。虽然对这种想法赞不绝口。