Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass a block of code as a macro argument?

Tags:

c

I'd like to wrap some lines of code with some boilerplate code, so should I do it by passing multiple lines of code as a macro argument like so:

#define safeRun(x) if (ValidationOK()) {x} 

int main(int argc, char **argv) {
    safeRun(
        foo();
        bar();
    )
}

Many thanks.

like image 301
mchen Avatar asked Jan 16 '13 07:01

mchen


People also ask

How many arguments macro can have?

For portability, you should not have more than 31 parameters for a macro. The parameter list may end with an ellipsis (…).

How many arguments we pass in macro definition?

macro (array[x = y, x + 1]) passes two arguments to macro : array[x = y and x + 1] .

Which is a valid type of arguments in macro?

There are two types of arguments: keyword and positional. Keyword arguments are assigned names in the macro definition; in the macro call, they are identified by name.

How do you pass a macro as a parameter?

Passing parameters to a macro. A parameter can be either a simple string or a quoted string. It can be passed by using the standard method of putting variables into shared and profile pools (use VPUT in dialogs and VGET in initial macros).


1 Answers

As written, your code will run foul of comma operators (but not, as previously claimed, commas in a function argument list).

Assuming you use C99, you can evade even that problem with variable arguments in the macro:

#define safeRun(...) if (ValidationOK()) {__VA_ARGS__}

int main(int argc, char **argv) {
    safeRun(
        foo(a, b),
        bar(c, d);
    )
}

Now, as far as the preprocessor is concerned, there are 2 arguments to the macro, separated by the commas, but they are handled as you want. Here's the gcc -E output:

# 1 "x3.c"
# 1 "<command-line>"
# 1 "x3.c"


int main(int argc, char **argv) {
    if (ValidationOK()) {foo(a, b), bar(c, d);}



}

Whether what you're proposing is a good idea is a separate discussion; these are the mechanisms that will more or less make it work.

like image 84
Jonathan Leffler Avatar answered Sep 24 '22 13:09

Jonathan Leffler