我的宏功能出了什么问题?

时间:2011-07-28 03:20:55

标签: c++ macros c-preprocessor newline

我使用行连续符“\”定义了一个多行宏函数,如下所示:

#define SHOWMSG( msg ) \ 
{ \     
    std::ostringstream os; \     
    os << msg; \     
    throw CMyException( os.str(), __LINE__, __FILE__ ); \ 
}

但它无法通过编译。顺便说一下,我正在使用VS2008编译器。你能告诉我上述宏功能有什么问题吗?

3 个答案:

答案 0 :(得分:6)

多语句宏的常用方法如下:

#define SHOWMSG(msg)                                  \
do {                                                  \
    std::ostringstream os;                            \
    os << msg;                                        \
    throw CMyException(os.str(), __LINE__, __FILE__); \
} while (0)

如果没有这个,结束括号后面的分号会导致语法问题,例如:

if (x)
    SHOWMSG("This is a message");
else
    // whatever

使用您的代码,这将扩展为:

if (x) {
    std::ostringstream os;
    os << "This is a message";
    throw CMyException(os.str(), __LINE__, __FILE__);
}
;    // on separate line to emphasize that this is separate statement following
     // the block for the if statement.
else
    // whatever

在这种情况下,分号将在if语句中的块后面形成一个空语句,而else将没有if来匹配。

答案 1 :(得分:1)

反斜杠必须是该行的最后一个字符才能继续行。

你的一些反斜杠后面有空格。

答案 2 :(得分:0)

在Visual Studio编辑器中点击Ctrl+Shift+8并查看尾随\后出现的任何空格 - 删除它们!

相关问题