Code Painters The Art of Coding

23Apr/140

Poor man’s RAII for C

The RAII pattern is well known in the C++ world, it's also a thing I'd love to have in plain old C, to avoid all those pesky resource cleanup code.

But hey, it's never too late to learn some new compiler features! Have you ever heard of the cleanup variable attribute available in GCC?

Let's see it in action:

#include <stdio.h>

void scoped(int * pvariable) {
  printf("variable (%d) goes out of scope\n", *pvariable);
}

int main(void) {
  printf("before scope\n");
  {
    int watched __attribute__((cleanup (scoped)));
    watched = 42;
  }
  printf("after scope\n");
}

When executed, this code prints the following:

before scope
variable (42) goes out of scope
after scope

Pretty cool, huh? And clang supports it, too.

Tagged as: , No Comments