【问题标题】:error: not assignable in macro function错误:不能在宏函数中赋值
【发布时间】:2016-06-16 21:48:49
【问题描述】:

我正在尝试将函数写入宏,但它给了我一个“不可分配的错误”。我的宏是这样的:

#define swapmacro(t, x, y) {t temp = x; x = y; y = temp;}

这是我调用它的代码

int x = 4;
int y = 5;
swapmacro(int, 4, 5);

然后它给了我这个错误信息:

stack.c:23:3: error: expression is not assignable
swapmacro(int, 4, 5);
^              ~
stack.c:7:43: note: expanded from macro 'swapmacro'
#define swapmacro(t, x, y) {t temp = x; x = y; y = temp;}
                                          ^
stack.c:23:3: error: expression is not assignable
swapmacro(int, 4, 5);
^                 ~
stack.c:7:50: note: expanded from macro 'swapmacro'
#define swapmacro(t, x, y) {t temp = x; x = y; y = temp;}
                                                 ^

【问题讨论】:

  • 你的意思是 swapmacro(int, x,y)
  • 我可以建议为罕见的边缘情况保留宏并使用函数吗?优化器将内联它或尽可能多地剥离它的调用开销真的很好吗?一个原因:使用调试器很容易检查函数。宏,没那么多。

标签: c++ macros c-preprocessor


【解决方案1】:
swapmacro(int, 4, 5);

扩展为:

{int temp = 4; 4 = 5; 5 = temp;};

4 = 55 = temp 都不是有效的表达式。整数文字不能是左值。也许你打算这样做:

swapmacro(int, x, y);

【讨论】:

    【解决方案2】:

    为什么不求助于使用宏的东西?

    swap

    所以代码可以是

    std::swap(x,y);
    

    具有类型安全等

    【讨论】:

    • 谢谢。我不认为它一定会使程序更有效率。我只是想知道宏。
    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    相关资源
    最近更新 更多