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 求平方感到困惑
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
