"with" macro in C

I was looking for a macro that would look like a design. Usage should look something like this:

with (lock(&x), unlock(&x)) {
    ...
}

This may be useful for some other purposes.

I came up with this macro:

#define __with(_onenter, _onexit, v) \
    for (int __with_uniq##v=1; __with_uniq##v > 0; )\
        for (_onenter; __with_uniq##v > 0; _onexit) \
            while (__with_uniq##v-- > 0)

#define _with(x, y, z) __with(x, y, z)
#define with(_onenter, _onexit) _with(_onenter, _onexit, __COUNTER__)

It has 3 nested loops because it should:

  • Initialize the loop counter (only C99, of course)
  • It is possible to initialize the _onenter variable (e.g., with (int fd=open(..), close(fd)))
  • Allow breakinside the code block. ( continue), and the macro can be adjusted to assert()it)

I used it for code for OS XV6 and it seems quite useful.

My question is: what are the worst problems with such a macro? I mean, besides just using the C macro (especially the one that implements the new control flow design).

So far, these flaws / problems have been discovered:

  • return goto ( goto )
  • (, fd < 0). , .
  • gnu89/c99 ( . )
  • , -. , .

? C?

+5
1

. , goto s.

, C , , , . . , .

, , gotchas. , " return goto ", "break , ". , .

, . clang, . .

GCC Clang, cleanup. :

lock_t x = NULL __attribute__((cleanup(unlock)));
lock(&x);

unlock , . , return goto, C/++.

+6

All Articles