abu*_*abu 14 c c++ macros c-preprocessor
这个问题在模拟面试中被问到了......真的很惊讶地找到了尴尬的答案......
考虑一个宏:
#define SQR(x) (x*x)
Run Code Online (Sandbox Code Playgroud)
例1:
SQR(2) //prints 4
Run Code Online (Sandbox Code Playgroud)
例2:
如果给出SQR(1 + 1),它不会求和(1+1)
,2
而是......
SQR(1+1) //prints 3
Run Code Online (Sandbox Code Playgroud)
尴尬吧?是什么原因?这段代码是如何工作的?
注意:我搜索了SO,但找不到任何相关问题.如果有任何好评请分享!
Luc*_*ore 47
SQR(1+1)
expands to 1+1*1+1
which is 3, not 4, correct?
A correct definition of the macro would be
#define SQR(x) ((x)*(x))
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
Furthermore: SQR(i++)
would be undefined behavior if SQR
is a macro, and completely correct if SQR
is a function.
归档时间: |
|
查看次数: |
12891 次 |
最近记录: |