[英]please explain this c code snippet mult(x,y)x*y?
#include <stdio.h>
#define mult(x,y)x*y /* what does this mean ?? */
int main()
{
int a,b,answer;
b=5;
a=5;
answer=mult(a+b,a+b);
printf("%d",answer);
return 0;
}
I'm using compiler gcc-4.9.2 我正在使用编译器gcc-4.9.2
If I understand correctly you want to know what #define mult(x,y) x*y
does. 如果我正确理解,您想知道#define mult(x,y) x*y
作用。
This a definition of a macro, during the compilation the compiler will replace, everywhere in the code, mult(x, y)
by x*y
. 这是一个宏定义,在编译期间,编译器将在代码中的任何地方将mult(x, y)
替换为x*y
。
In your code: answer=mult(a+b,a+b);
在您的代码中: answer=mult(a+b,a+b);
Will be replaced by: answer=a+b*a+b;
将替换为: answer=a+b*a+b;
Whence the answer will be 35
. 答案将是35
。
A correct way to use macros and to ensure they work properly is to include parentheses where they might be needed. 使用宏并确保其正常工作的正确方法是在可能需要的地方添加括号。
Therefore your define would be: #define mult(x, y) ((x)*(y))
to ensure the result is what you would expect 100
因此,您的定义将是: #define mult(x, y) ((x)*(y))
以确保结果符合您的期望100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.