Reputation: 22846
I came across this interesting article about an obscure (to me, at least) Clang GCC extension.
They say that a block enclosed in parentheses returns a value, like...
UIButton *button = ({
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(someSelector:)
forControlEvents:UIControlEventTouchUpInside];
button;
});
It's very hard to find documentation for this (there's very little on the net and on the Clang website).
Does anyone know if it safe to use? If not, why?
Also, does it cause retain cycles like Objective-C blocks?
Upvotes: 2
Views: 884
Reputation: 54533
In gcc's documentation, that is a special form of compound statement, which is informally defined as follows:
A compound statement enclosed in parentheses may appear as an expression in GNU C. This allows you to use loops, switches, and local variables within an expression.
Recall that a compound statement is a sequence of statements surrounded by braces; in this construct, parentheses go around the braces.
Later in the section, this is referred to as a statement expression, but in the part where it is defined, the term is not used.
For instance, compare with the description from gcc 2.7.2.3:
Statements and Declarations in Expressions
==========================================
A compound statement enclosed in parentheses may appear as an
expression in GNU C. This allows you to use loops, switches, and local
variables within an expression.
(there is no "statement expression" term there—and current gcc source is much the same, with scattered comments about the feature, but no formal definition).
It has been a gcc extension (not standard C) for a long time (it's mentioned in gcc 1.35 from 1989). I first saw it used in Midnight Commander in the mid-1990s (making it unsuitable for use in $dayjob
). If all you care about is gcc and clang, then it is "safe" in the sense that it probably will not be removed from the compiler.
On the other hand (see the documentation), it is noted that the feature is probably not a good thing to use in C++ programs.
Here are a few relevant links:
Upvotes: 1