在 c 中对宏 SQR 求平方感到困惑 [英] Confused by squaring macro SQR in c

查看:17
本文介绍了在 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 求平方感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆