Question

I was looking for a macro that will resemble the with-construct. The usage should be something like:

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

It might 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:

  1. Initialize loop counter (C99 only, of course)
  2. Possibly initialize variable _onenter (such as with (int fd=open(..), close(fd)))
  3. Allow break inside the code block. (continue is allowed too. And the macro could be adjusted to assert() it out)

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

My question is - what are the worst problems with such a macro? I mean, besides the mere usage of a C macro (especially one that implements new control-flow construct).

So far have found these drawbacks / problems:

  1. No support for return or goto (but it can save some gotos in kernel code)
  2. No support for errors (such as fd < 0). I think this one is fixable.
  3. gnu89 / c99 and above only (loop counter. the unique variable trick is not necessary)
  4. Somewhat less efficient than simple lock-unlock. I believe it to be insignificant.

Are there any other problems? Is there a better way to implement similar construct in C?

Was it helpful?

Solution

That macro scares me. I'd prefer the traditional approach using gotos.

That approach is primitive, but most C programmers are familiar with the pattern and if they're not, they can understand it by reading the local code. There is no hidden behavior. As a consequence, it's pretty reliable.

Your macro is clever, but it would be new to most everybody and it comes with hidden gotchas. New contributors would have to be thought rules such as "don't return or goto out of a with block" and "break will break out of the with block, not out of the surrounding loop". I fear mistakes would be common.

The balance would shift if you could add warnings for misuses of this construct to the compiler. With clang, that seems to be an option. In this case, misuses would be detected and your code would remain portable to other compilers.

If you're willing to restrict yourself to GCC and Clang, you can use the cleanup attribute. That would make your example look like this:

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

And unlock will be called with a pointer to the variable when it goes out of scope. This is integrates with other language features like return and goto, and even with exceptions in mixed C/C++ projects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top