简体   繁体   中英

How can I define, in the C programming language, a FIRST macro that let's me declare scoped variables?

I have the following macros

#define FIRST(first) \
 switch(first, 0) default:

#define LAST(last) \
 switch(0) for(;0;last) default:

#define BRACKET(first, last) \
 switch(first, 0) for(;0;last) default:

And they are used like so.

#include <stdio.h>

// ... Macros are defined here

int main (int argc, const char * argv[])
{
    int x;

    FIRST(x = 4)
    {
        printf("%i\n", x);
    }

    LAST(++x)
    {
        printf("%i\n", x);
    }

    printf("%i\n", x);

    return 0;
}

BRACKET is simply a combination of FIRST and LAST. The FIRST macro, (and the BRACKET macro), isn't good enough though. I'd like to be able to write the following code where y is scoped to the curly braces.

    FIRST(int y = 0)
    {
        printf("%i\n", y);
    }

How can I write a FIRST macro, in the C programming language that lets me declare a variable scoped within the curly braces?

Some corner cases are:

I want the following code snippet allowed

FIRST(int x = 0)
 printf("%i\n", x);

I want the folllowing code snippet disallowed

FIRST(int x = 0)
 printf("%i\n", x);

++x;
printf("%i\n", x);

PS I'm surprised that "switch(0) for(;0;last) default:" is accepted by the compiler, is this really legal C code?

To obtain scoped variables in the way you want is easy if you have a compiler that is at least complying to C99. (otherwise don't do it, or get yourself a modern compiler).

A prefix to a block or statement like FIRST(int y = 0) can be realized by something like

for (int t = 0; t < 1; ++t)
  for(int y = 0; t < 1; ++t)

that is you define an auxiliary variable that controls the loop to be executed exactly once. Modern compilers easily optimize the noise that comes with this and go to the essential.

With some care you can pack that into a macro, where you should take care that the name also captures what is going on and that you don't hurt the eyes of your fellow programmers. In particular put a big warning label somewhere that such things change the semantic of break and continue statements to something quite surprising for the unaware reader.

I have written up more on scope bound resource management with for -scopes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM