能否范围被包裹在括号用C返回一个值? [英] Can scopes be wrapped in parentheses and return a value in C?

查看:125
本文介绍了能否范围被包裹在括号用C返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我抬头 MIN Mac OS X上的定义,并发现这一点:

I looked up the definition of MIN on Mac OS X and found this:

#define MIN(A,B) ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __a : __b; })

这是起初并不那么明显,但是当它扩展,它变成一些看起来非常奇怪,我说:

It's not so obvious at first, but when it expands, it turns into something that looks extremely strange to me:

int a = 1, b = 2;
// int min = MIN(a, b);
int min = ({
    int __a = (a);
    int __b = (b);
    __a < __b ? __a : __b;
});

这是,的确,一个范围裹成一个前pression的收益,最后当然pression的价值。它似乎工作,至少铛,随着范围内pretty太多任意code:

This is, indeed, a scope wrapped into an expression that "returns" the value of the last expression. It seems to work, at least with clang, with pretty much arbitrary code inside the scope:

int a = ({
    time_t x = time(NULL);
    if (x % 3 == 1)
        x++;

    x % 10;
});

我以前从未见过这一点,我在想,如果它是标准的。我知道一个事实,即Visual Studio将不会接受,但话又说回来,Visual Studio是套牢C89,所以这不是很说明问题。

I had never seen this before, and I was wondering if it's standard. I know for a fact that Visual Studio won't accept it, but then again, Visual Studio is stuck with C89, so that's not very telling.

推荐答案

这是一个GCC扩展标准C叫的声明前pressions 的。是的,你可以使用它,如果你只需要支持GNU编译器(它是跨平台的)。如果你要坚持标准C,你不会使用的符号。

This is a GCC extension to standard C called Statement Expressions. Yes, you can use it if you only need to support GNU compilers (and it is cross-platform). If you need to stick to standard C, you won't use the notation.

这篇关于能否范围被包裹在括号用C返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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