Confused by squaring macro SQR in c(在 c 中对宏 SQR 求平方感到困惑)
问题描述
这个问题是在一次模拟面试中被问到的......真的很惊讶地发现了尴尬的答案......
This question was asked to me in a mock interview...Really got surprised to find awkward answers...
考虑一个宏:
#define SQR(x) (x*x)
示例 1:
SQR(2) //prints 4
示例 2:
如果给定 SQR(1+1),它不会将 (1+1)
与 2
相加,而是...
If SQR(1+1) is given it doesn't sum (1+1)
to 2
but rather ...
SQR(1+1) //prints 3
尴尬吧?是什么原因?这段代码是如何工作的?
Awkward right? What is the reason? How does this code work?
注意:我搜索了 SO,但找不到任何相关问题.如果有什么好心的请分享!
NOTE: I searched SO but couldn't find any relevant questions. If there are any kindly please share it!
推荐答案
SQR(1+1)
展开为 1+1*1+1
即 3,不是4,对吗?
SQR(1+1)
expands to 1+1*1+1
which is 3, not 4, correct?
宏的正确定义是
#define SQR(x) ((x)*(x))
扩展为 (1+1)*(1+1)
并且,更重要的是,向您展示了不应使用宏的原因之一不需要.以下更好:
which expands to (1+1)*(1+1)
and, more important, shows you one of the reasons you shouldn't use macros where they aren't needed. The following is better:
inline int SQR(int x)
{
return x*x;
}
此外:如果 SQR
是宏,则 SQR(i++)
将是 未定义的行为,如果 SQR
则完全正确code> 是一个函数.
Furthermore: SQR(i++)
would be undefined behavior if SQR
is a macro, and completely correct if SQR
is a function.
这篇关于在 c 中对宏 SQR 求平方感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 c 中对宏 SQR 求平方感到困惑


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01