c++ - 我的宏函数有什么问题?

标签 c++ macros c-preprocessor newline

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

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

但它无法通过编译。顺便说一句,我正在使用 VS2008 编译器。请问我上面的宏函数有什么问题吗?

最佳答案

多语句宏的常用方法是这样的:

#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 语句 block 之后形成一个空语句,而 else 不会有 if 匹配。

关于c++ - 我的宏函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6853751/

相关文章:

c++ - 什么规则控制将 static_cast<float> 应用于 double 的舍入行为?

c - 有没有办法在 C 预处理器宏中使用 'escape' 符号?

c - 哪个 boost 宏允许我在程序中插入可变数量的语句

c - 无法使用 ifdef 宏初始化结构内部的数组

C 宏扩展命令

c++ - 如何定位可执行文件中函数所在的位置?

c++ - 未限定范围的多行 MACROS 的危险

c++ - 回溯在这段代码中是如何工作的

c++ - 标识符和宏有什么区别?

C 预处理器 token 替换因解析错误而失败