你可以将#define扩展为字符串文字吗?

Ada*_*lor 12 c++ c-preprocessor

有没有办法让C++预处理器将#define'ed值扩展为字符串文字?
例如:

#define NEW_LINE '\n'
Printf("OutputNEW_LINE"); //or whatever
Run Code Online (Sandbox Code Playgroud)

这对我来说在编译之前它应该是可能的吗?
或者是否有更好的设计模式来实现这种行为(不需要像sprintf那样使用运行时修复)?

编辑我明白#define可能是邪恶的,但为了论证缘故...

其他有没有人批评这种方法?

Ric*_*dle 25

这样做:

#define NEW_LINE "\n"         // Note double quotes
Printf("Output" NEW_LINE);
Run Code Online (Sandbox Code Playgroud)

(从技术上讲,它是编译器加入字符串而不是预处理器,但最终结果是相同的.)


Tho*_*erg 6

如果我没记错的话

Printf("Output" NEW_LINE);
Run Code Online (Sandbox Code Playgroud)

  • 是的,C编译器将自动连接相邻的字符串文字,虽然#define应该将NEW_LINE定义为"\n"而不是'\n'以使其工作,我想. (3认同)