通过在平方c宏SQR困惑 [英] Confused by squaring macro SQR in c

查看:83
本文介绍了通过在平方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

尴尬吧?是什么原因?这是如何code的工作?

Awkward right? What is the reason? How does this code work?

请注意:我搜索左右,但找不到任何有关问题。如果有任何好心请与大家共享!

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)更重要,你展示了你不应该的原因之一并不需要它们的地方'T使用宏。以下是更好的:

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 是一个宏,完全正确的,如果 SQR 是一个函数。

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天全站免登陆