GNU C provides several language features not found in standard C. These extensions are available in C and Objective-C.
There's a GCC C extension (known as statement expressions) that causes a sequence of statements surrounded by braces to return a value if they're also surrounded by parentheses:
self.searchBar = ({
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:({
CGRect frame = self.tableView.frame;
frame.size.height = 100.0f;
frame;
})];
searchBar.delegate = self;
searchBar;
});
In this construct, the parentheses go around the braces. The value of the last statement serves as the value of the entire construct, so we can use it for initialization and assignment, among other things.
There's a lot of advantages to this construct for initialization:
- clear and concise
- configuration details in the initialization
- scope is smaller
- generic variable names can be reused
Is there any downside, or should this be standard practice? Should we all be doing this from now on?