如何创建一个具有多行代码的宏? [英] How to create a macro with multiple lines of code?

查看:86
本文介绍了如何创建一个具有多行代码的宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个将注入一些代码的宏,如:

I want to make a macro which will inject some code, like:

if (foo) {
[Bar fooBar];
}

然后,在我需要的地方,我把FOOBAR放在代码中。不确定,但是在编译时,编译器将替换为实际代码,就像上面的例子。

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

推荐答案

使用\来逃避每一个换行符

Use \ to escape each line-break you want to be part of the macro.

但是,请注意,使用这样的宏可以隐藏结构,如果你不小心。以你的例子:

However, be aware that using macros like this can hide structure if you aren't careful. Taking your example:

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

猜猜这个扩展的内容。可能不是你的想法。这里是编译器看到的(缩进调整):

Guess what this expands to. Probably not what you think. Here's what the compiler sees (indentation adjusted):

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

糟糕!这个分号是一个单独的,空的语句。每个 if 只需要一个语句;第一个如果的语句是第二个 if ,第二个 if 的语句是复合语句( {...} ),所以他们都满足了他们的配额,留下了分号。

Oops! That semicolon is a separate, empty statement. Each if takes only one statement; the first if's statement is the second if, and the second if's statement is the compound statement ({…}), so they have both met their quota, leaving the semicolon out.

因此,分号不会绑定到如果 -it的无条件。当您尝试将 else 应用于无条件语句时,会导致语法错误。

So the semicolon is not bound to an if—it's unconditional. That causes a syntax error when you then try to apply the else to an unconditional statement.

修复,因为它是将 FOOBAR 的内容包装在 do ... while 语句中:

The fix, ugly as it is, is to wrap the contents of FOOBAR in a do…while statement:

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

在宏定义中的分号, do ... while 是一个未终止的语句,因此在宏使用之外的分号将绑定到它。然后我们扩展的代码看起来像这样:

Because we leave out the semicolon in the macro definition, the do…while is an unterminated statement, so that the semicolon outside the macro usage will bind to it. Then our expanded code looks like this:

//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)

这篇关于如何创建一个具有多行代码的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆