C ++中的多语句宏 [英] Multi-statement Macros in C++
问题描述
在C ++ 中,是否可以像下面这样创建一个带有 nested if语句的多语句宏?我已经尝试了一段时间,第二个if语句无法看到' symbol ',我遇到了范围问题.也许我需要进一步了解宏.
In C++, is it possible to make a multi-statement macro with nested if statements inside of it like the one below? I've been attempting it for a while now and I'm getting a scope issue for the second if statement not being able to see 'symbol'. Maybe I need to understand macros further.
#define MATCH_SYMBOL( symbol, token)
if(something == symbol){
if( symbol == '-'){
}else if (symbol != '-'){
}
other steps;
}
推荐答案
对于多行宏,您需要在除最后一行以外的所有末尾添加\
字符,以告诉宏处理器继续解析下一行中的宏,如下所示:
For a multi-line macro you need to add a \
character to the end of all but the last line to tell the macro processor to continue parsing the macro on the next line, like so:
#define MATCH_SYMBOL( symbol, token) \
if(something == symbol){ \
if( symbol == '-'){ \
}else if (symbol != '-'){ \
} \
other steps; \
}
现在,它试图将其解释为1行宏,然后在文件顶部显示一些实际代码,这不是您想要的:
Right now, it's trying to interpret it as a 1-line macro and then some actual code at the top of your file, which isn't what you want:
#define MATCH_SYMBOL( symbol, token)
// and then... wrongly thinking this is separate...
if(something == symbol){ // symbol was never defined, because the macro was never used here!
if( symbol == '-'){
}else if (symbol != '-'){
}
other steps;
}
这篇关于C ++中的多语句宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!