在 c 中对宏 SQR 求平方感到困惑

2022-01-11 00:00:00 c macros c++ c-preprocessor

这个问题是在一次模拟面试中被问到的......真的很惊讶地发现了尴尬的答案......

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.

相关文章