4

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?

Rudiger
  • 6,634
  • 9
  • 40
  • 57
  • 1
    They are called [statement expressions](http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html), as far as I know Clang supports them with `-std=gnu99` – Joe Dec 31 '13 at 21:05
  • Should we and can we are two very different creatures, and I'd argue that it's a matter of opinion. It's a very cool extension IMO, but that doesn't mean you should be refactoring everything to use it. – CodaFi Dec 31 '13 at 21:12
  • Portability is not a high priority in the iOS ecosystem (and why not?), so I'd use the statement expressions. – Rhythmic Fistman Dec 31 '13 at 21:33
  • 1
    I don’t think that there’s anything wrong with using them, but I would prefer to use named initializers for structure creation (as they’re standard and more portable), and the particular example here can be done much more cleanly without using any tricks at all. – Stephen Canon Jan 02 '14 at 21:42

0 Answers0