Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can scopes be wrapped in parentheses and return a value in C? [duplicate]

Tags:

c

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;
});

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;
});

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.

like image 647
zneak Avatar asked May 15 '13 17:05

zneak


People also ask

What are declared after the function name and inside parentheses?

Therefore, you have to put brackets after the function name to declare the arguments. Brackets used for passing argument When you want to declare a function brackets used whenever you pass arguments or not. That is a part of function declaration.

Does Python have block scope?

Local (or function) scope is the code block or body of any Python function or lambda expression. This Python scope contains the names that you define inside the function. These names will only be visible from the code of the function.


1 Answers

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.

like image 199
Jonathan Leffler Avatar answered Nov 02 '22 02:11

Jonathan Leffler