Gol*_*Lee 0 c++ macros newline c-preprocessor
我使用行连续字符"\"定义了一个多行宏函数,如下所示:
#define SHOWMSG( msg ) \
{ \
std::ostringstream os; \
os << msg; \
throw CMyException( os.str(), __LINE__, __FILE__ ); \
}
Run Code Online (Sandbox Code Playgroud)
但它无法通过编译.顺便说一下,我正在使用VS2008编译器.你能告诉我上述宏功能有什么问题吗?
多语句宏的常用方法如下:
#define SHOWMSG(msg) \
do { \
std::ostringstream os; \
os << msg; \
throw CMyException(os.str(), __LINE__, __FILE__); \
} while (0)
Run Code Online (Sandbox Code Playgroud)
没有它,关闭括号后面的分号会导致语法问题,例如:
if (x)
SHOWMSG("This is a message");
else
// whatever
Run Code Online (Sandbox Code Playgroud)
使用您的代码,这将扩展为:
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
Run Code Online (Sandbox Code Playgroud)
在这种情况下,分号将在语句中的块后面形成一个空if语句,并且else不会if与之匹配.