简体   繁体   English

为什么这个 C 宏 function 计算 2 个数字的和会产生错误?

[英]Why does this C macro function calculating sum of 2 numbers generate error?

I have a piece of code to calculate sum of 2 numbers using #define below:我有一段代码使用下面的#define来计算 2 个数字的总和:

#include <stdio.h>

#define sum(a, b) \
    int res = 0;    \
    res += (a + b); \
    (res ? res : 0)

int main () {
    printf("%d ", sum(3, 4));
    return 0;
}

When I compiled upper code, I caught this error:当我编译上层代码时,我发现了这个错误:

error: expected expression before 'int'
     int res = 0;    \
note: in expansion of macro 'sum'     
     printf("%d ", sum(3, 4));

So, what did this error mean?那么,这个错误是什么意思呢? And, how can I fix this?而且,我该如何解决这个问题?

Thank you谢谢

If you run your program through C preprocessor like gcc -E program.c then you will have following towards end:如果你通过 C 预处理器运行你的程序,比如gcc -E program.c那么你将在最后得到以下结果:

int main () {
    printf("%d ", int res = 0; res += (3 + 4); (res ? res : 0));
    return 0;
}

which is invalid code.这是无效的代码。

To fix this you need to fix the macro for sum要解决此问题,您需要修复sum的宏

#include <stdio.h>

#define sum(a, b) ((a) + (b))

int main () {
    printf("%d ", sum(3, 4));
    return 0;
}

You need to use parentheses to counter against potential misuse of operator precedence for operators like ++ or --.您需要使用括号来防止可能滥用运算符优先级的运算符,如 ++ 或 --。 It is not a problem here but in general it is a good practice.这在这里不是问题,但总的来说这是一个很好的做法。

A better choice would be to write an inline function for this kind of work.更好的选择是为此类工作编写内联 function。

If you use GCC then it has a non-standard and therefore non-portable extension that allows statement expressions , which allows you to put multiple statements in an expression.如果您使用 GCC 那么它有一个非标准的因此不可移植的扩展,它允许statement expressions ,它允许您将多个语句放在一个表达式中。

I don't really recommend its use, but it is possible to do what you want as a macro:我真的不推荐使用它,但可以作为宏来做你想做的事:

#define sum(a, b) \
    ({ int res = 0;    \
       res += (a + b); \
       (res ? res : 0) })

But the proper solution is to use functions instead, and rely on the compiler to properly inline it (with a little "hint" from you):但正确的解决方案是改用函数,并依靠编译器正确地内联它(你有一点“提示”):

inline int sum(int a, int b)
{
    return a + b;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM