通过在c中平方宏SQR而感到困惑

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.

  • 当然,即使是"修正过的"宏在评估参数两次时仍然会让你感到惊讶. (3认同)

Dev*_*lus 6

问题是宏在编译之前正在进行文本替换,因此宏扩展为 1+1*1+1


Phi*_* T. 6

这就是为什么你总是把参数放到宏中():

#define SQR(x) ((x)*(x))
Run Code Online (Sandbox Code Playgroud)