这个C代码的输出是49但有人可以解释我怎么做吗?

#include <stdio.h>

#define CUBE(x) (x * x * x)

int main() {
    printf("%d", CUBE(4+5));
    return 0;
}

回答

以下是宏在编译过程中的展开方式:

printf("%d", (4+5 * 4+5 * 4+5));

因为*具有比 更高的优先级+,所以这个表达式被计算为(4 + (5 * 4) + (5 * 4) + 5),产生49而不是预期的729

为避免此类运算符优先级问题,所有宏参数都必须在宏定义以及表达式本身中用括号括起来:

#define CUBE(x)  ((x) * (x) * (x))

但是请注意,这种扩展会CUBE计算x多次,如果宏参数有副作用,例如CUBE(i++).

为了避免所有这些问题,请使用一个函数并让编译器对其进行优化:

int cube(int x) {
    return x * x * x;
}

您可以static inline在此函数定义前添加,但现代优化器仍会在没有此内容的情况下内联该函数。


回答

宏会将代码变为:

printf("%d", (4+5 * 4+5 * 4+5));

这是有效的:

printf("%d", 4 + (5*4) + (5*4) + 5); // 29

如果你想立方体9得到729,你应该写CUBE((4+5))

  • Or stop using function-like macros. In today's world of optimising compilers, just write it as a function, the compiler will inline it if the benefits are enough (and you can even suggest that to the compiler with `inline`).
  • Re “ If you want 729, you should write CUBE((4+5))”: No, the macro should be written with parentheses so its user does not have to supply them.
  • @Eric, the amount of macro magic to cover *all* cases (such as `CUBE(x++)`, for example) make function-like macros a very bad idea. Better to just ditch them, use macros for simple definitions, and inline-suggested functions for everything else.

以上是这个C代码的输出是49但有人可以解释我怎么做吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>