This question already has answers here:
Closed 2 years ago.
The need for parentheses in macros in C [duplicate]
(8个答案)
Square of a number being defined using #define
(11个答案)
C #define macros
(7个答案)
所以我明天有个考试,我的问题遇到了这个问题。
我的问题是,为什么输出是8而不是20。
因为当我用
当
==>z=3+1*4+1=8
最佳实践是用括号将每个宏参数括起来。在你的例子中(为了达到预期的结果),应该是:
(8个答案)
Square of a number being defined using #define
(11个答案)
C #define macros
(7个答案)
所以我明天有个考试,我的问题遇到了这个问题。
#define mul(x,y) (x * y)
#include <stdio.h>
#include <string.h>
int main()
{
int x = 3;
int y = 4;
int z = 0;
z = mul(x+1, y+1);
printf("4 * 5 = %d \n", z);
return 0;
}
我的问题是,为什么输出是8而不是20。
因为当我用
z= mul(x+1,y+1)
替换z= mul((x+1),(y+1))
时,我得到的正确答案是20 最佳答案
Macro#define mul(x,y) (x * y)
实际上告诉预编译器,如果它找到字符串mul(任何模式X,任何模式Y),它应该用(任何模式X*任何模式Y)替换它。
你的例子里有什么?
int x = 3;
int y = 4;
int z = 0;
z = mul(x+1, y+1);
当
mul
被替换后,您将得到int x = 3;
int y = 4;
int z = 0;
z = x+1*y+1;
==>z=3+1*4+1=8
最佳实践是用括号将每个宏参数括起来。在你的例子中(为了达到预期的结果),应该是:
#define mul(x,y) ((x) * (y))