How to create a macro with several lines of code?

I want to make a macro that will enter some code, for example:

if (foo) {
[Bar fooBar];
}

and then where I need it, I put FOOBAR in the code. Not sure, but at compile time, the compiler replaces this with actual code, as in the example above. Maybe there is something other than a macro that I could use for this?

+3
source share
2 answers

Use \ to avoid every line break that you want to be part of the macro.

However, keep in mind that using such macros can hide the structure if you are not careful. Example:

if (bar)
    FOOBAR();
else
    do_something_else();

, . , , . ( ):

if (bar)
    if (foo)
        {
            [Bar fooBar];
        }
;
    else
        do_something_else();

Oops! . if ; if if, if ({…}), , .

, if -it . , else .

, , , , FOOBAR do…while:

#define FOOBAR()       \
    do {                \
        if (foo)         \
            [Bar fooBar]; \
    } while(0) /*semicolon omitted*/

, do…while - , . :

//First, the unexpanded code again
if (bar)
    FOOBAR();
else
    do_something_else();

//Expanded
if (bar)
    do
        {
            if (foo)
                [Bar fooBar];
        }
    while(0);
else
    do_something_else();

else if (bar), .

+8

, \ , . , , .

+5

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


All Articles