我刚刚浏览了面试中经常被问到的某些代码。我提出了一些问题,是否有人可以帮助我解决这个问题?
我现在对此很困惑,
#include <stdio.h>
#include <conio.h>
#define square(x) x*x
main()
{
int i, j;
i = 4/square(4);
j = 64/square(4);
printf("\n %d", i);
printf("\n %d", j);
printf("\n %d", square(4));
getch();
}
输出是:
4
64
16
我想知道,为什么 square(4)
分割时返回 1?我的意思是,如何在除法时得到值 4 和 64,但直接使用时得到 16!!?
最佳答案
square
未加括号:它按文本展开,所以
#define square(x) x*x
...
i=4/square(4);
表示
i=4/4*4;
哪些分组为 (4/4) * 4
。要修复,请添加括号:
#define square(x) ((x)*(x))
仍然是一个非常不确定的 #define
,因为它对 x
求值两次,所以 square(somefun())
调用该函数两次并执行 < em>不一定因此必须计算一个平方,而是计算两个连续调用的乘积,当然;-)。
关于c - 使用#define 定义的数字的平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3719150/