Macro issue with multiple statements

#define RUN_SOME_STUFF(...) { \ int x = 0; \ printf("[INFO] Do some stuff here ... %d\n", ++x); \ {__VA_ARGS__} \ printf("[INFO] end some stuff here\n"); \ } 

How do I use it:

 ... RUN_SOME_STUFF( { // middle: int y; y = 100; printf("Middle\n"); }); ... 

Now I know that this is seen as a (very) ugly macro, but this is the main reason I seek help.

The first problem with this: if any type of error appears, the compiler will show the last line of the macro as an invalid line. Printouts are just examples to simplify the problem (in both code snippets), so there can be 20 lines of complex, embedded code, in which case it is very annoying.

The second is that __LINE__ is resolved in the same wrong way

& I'm sure there are many more ...

1. Is there a way to fix the above problems so that the strings are resolved correctly? (maybe some kind of compiler option?) I am using VS2008 / 2010)

2. If there is no way to do this using the macro in a โ€œcuteโ€ way, do I have any other options for this? I just want to run the code around (before and after) some other code.

Edit: I would often use this macro, always with a different โ€œaverageโ€ content, so I cannot write an inline function every time.

+4
source share
2 answers

You can split the macro into two parts. Not really, but it works when macros are paired. Below RUN_BEGIN; and RUN_END; written so that they need a semicolon.

 #define RUN_BEGIN \ do { \ int x = 0; \ printf("[INFO] Do some stuff here ... %d\n", ++x); \ { \ (void)0 #define RUN_END \ } \ printf("[INFO] end some stuff here: %d\n",x ); \ } while (0) 
+2
source

You would probably be lucky with function pointers . I did not compile this, but something like:

 void runSomeStuff(void (*stuff)(void)) { int x = 0; printf("[INFO] Do some stuff here ... %d\n", ++x); (*stuff)(); printf("[INFO] end some stuff here\n"); } 
0
source

Source: https://habr.com/ru/post/1386412/


All Articles