How to implement Go's defer() in C so that it allows declaring vars?

In this Modern C video there's a trick that allows to postpone execution of a code until the block/scope exits. It's used as follows:

int main()
{
    int foo=0, bar;
    const char *etc = "Some code before defer";

    defer(profile_begin(), profile_end())
    {
        /* Some code, which will be automatically 
         * preceded by call to profile_begin() and
         * followed by run of profile_end().*/
         foo++;
         bar = 1;
    }

    etc = "Some code after defer";
    foo = bar + 1;
}

Implementation from the video:

#define macro_var_line(name) concat(name, __LINE__)
#define defer(start,end) for( \
        int macro_var_line(done) = (start,0); \
        !macro_var_line(done); \
        (macro_var_line(done) += 1), end)

It's pretty simply implemented. What might be confusing is the macro_var_line(name) macro. Its purpose is to simply ensure that a temporary variable will have a unique, "obfuscated" name by adding current line number to it (of where defer is called).

However the problem is that one cannot pass code to start snippet that declares new variables, because it is pasted in the for() comma operator that already has an int type used (because of int macro_var_line(done) = …). So it's not possible to, eg.:

defer(FILE *f = fopen("log.txt","a+"), fclose(f))
{
    fprintf(f,"Some message, f=%p",f);
}

I would want to have such macro, capable of declaring new vars in start snippet. Is it achievable with standard C99, C11 or maybe some GCC extensions?



from Recent Questions - Stack Overflow https://ift.tt/3COuf3L
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation