News for hackers. Stuff that matters.
Re:Emulating Swift's “defer” in C, with Clang or GCC+Blocks by pcwalton on Saturday October 10, 2015 @12:07PM (#10365918)
Not the same semantics, as least compared to Golang. This is block-scoped, but "defer" in Go is function-scoped and has highly dynamic semantics—for example, call it in a loop and the compiler may not be able to statically prove how many times it will run.

(Note that, IMO, the semantics of the feature as implemented in the article are preferable to those of Golang, so I wouldn't personally go to the effort of trying to duplicate Go's behavior.)

Re:Emulating Swift's “defer” in C, with Clang or GCC+Blocks by cthrowappp on Saturday October 10, 2015 @01:54PM (#10366272)
Unless I'm mistaken, `__attribute__((cleanup))` is function-, not block-, scoped. The cleanup attribute is actually declared on the Block, which is kind of cute.

Instead, I'd suggest just making regular use of `__attribute__((cleanup))` in C under GCC or Clang and avoiding C blocks entirely. In this case you could do something like:

  #define AUTOCLOSE_FILE(n) __attribute__((cleanup(autoclose_file))) n = NULL
  
  void
  autoclose_file(FILE *f)
  {
    if (f)
      fclose(f);
  }
  
  int
  main(...)
  {
    FILE AUTOCLOSE_FILE(*a), AUTOCLOSE_FILE(*b);
  
    a = fopen("foo");
    if (!a)
      return;

    b = fopen("bar");
    if (!b)
      return;
  
    ...
  }