如何`({...})`返回一个值? [英] How does `({...})` return a value?

查看:153
本文介绍了如何`({...})`返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我发现这个GCC宏:

I recently found this GCC macro:

#define max(a,b) \
   ({ typeof (a) _a = (a); \
       typeof (b) _b = (b); \
     _a > _b ? _a : _b; })

我看到这个code之前,我并没有意识到,这code 块{...} 可以以某种方式在C.返回值结果
1)你能不能给我一个提示是如何工作的?

I didn't realize before I saw this code, that a block of code {...} can somehow return value in C.
1) Could you give me a hint how this works?

虽然,我通常能够通过滥用逗号运算符来实现同样的结果:

Though, I usually was able to achieve the same result by abusing the comma operator:

#define max(a,b) \
    (typeof (a) _a = (a), \
     typeof (b) _b = (b), \
     (_a > _b ? _a : _b)) 

,或者如果它仅是为副作用,我会用做{...}而(0)

2)什么是这样做的preferred方式?

推荐答案

({...}) 构建是一个GCC扩展。

The ({ ... }) construct is a gcc extension.

原来是 的typeof 运营商。

So is the typeof operator.

A MAX 宏(注意常规采用​​全大写的)是很容易写:

A MAX macro (note the conventional use of all-caps) is easy enough to write:

#define MAX(a, b) ((a) > (b) ? (a) : (b))

它做评估其参数不止一次之一,所以你不应该调用它,例如, MAX(X ++,Y - )。使用全大写的作用是提醒,这是一个宏,而不是功能的用户,并要小心副作用的参数。

It does evaluate one of its arguments more than once, so you shouldn't invoke it as, for example, MAX(x++, y--). The use of all-caps serves to remind the user that it's a macro, not a function, and to be careful about arguments with side effects.

或者你也可以写为每种类型的函数(也许内联的)。

Or you can write a function (perhaps an inline one) for each type.

这篇关于如何`({...})`返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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