Quantcast
Channel: Code Painters
Viewing all articles
Browse latest Browse all 11

Poor man’s RAII for C

$
0
0

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.


Viewing all articles
Browse latest Browse all 11

Latest Images

Trending Articles





Latest Images