简体   繁体   English

使用 std::cout 打印 #define 宏

[英]Print a #define macro using std::cout

I am trying to do this我正在尝试这样做

#define _TEST_ test
#include <iostream>

int main()
{
        std::cout << "_TEST_" << std::endl;
}

As far as my understanding, I expect this output.据我了解,我希望这个 output。

test

However, the output I get is但是,我得到的 output 是

_TEST_

Why am I doing wrong here?为什么我在这里做错了?

Macro expansion in the C/C++ preprocessor only happens to tokens. C/C++ 预处理器中的宏扩展只发生在标记上。 Variables names, for instance, are tokens.例如,变量名称是标记。 But the inside of a string is not a token;但是字符串内部不是标记; it's a part of a larger token (namely, the string literal itself).它是更大标记的一部分(即字符串文字本身)。

If you want the macro to expand to something within quotation marks, you need to use stringification .如果你想让宏扩展到引号内的东西,你需要使用stringification

#define xstr(x) str(x)
#define str(x) #x
#define _TEST_ test
#include <iostream>

int main()
{
        std::cout << xstr(_TEST_) << std::endl;
}

You can read the above link for why we need those extra two layers of indirection ( xstr and str ), but the basic idea is that # itself doesn't do macro expansion, so by calling xstr , we force a macro expansion of the argument ( _TEST_ into test , namely), and then separately we call str to stringify that.您可以阅读上面的链接了解为什么我们需要那些额外的两层间接( xstrstr ),但基本思想是#本身不进行宏扩展,因此通过调用xstr ,我们强制对参数进行宏扩展( _TEST_进入test ,即),然后我们分别调用str对其进行字符串化。 If we had just called str directly, it would see #_TEST_ and not perform macro expansion.如果我们只是直接调用str ,它会看到#_TEST_不会执行宏扩展。

"_TEST_" is a string literal and not a macro. "_TEST_"字符串文字而不是宏。 So no macro replacement will be done due to "_TEST_" .因此,由于"_TEST_" ,将不会进行任何宏替换。 To achieve your expected output you need to remove the surrounding double quotes and also change the macro to as shown below要实现预期的 output,您需要删除周围的双引号并将宏更改为如下所示

//-------------vvvvvv--->double quotes added here
#define _TEST_ "test" 
#include <iostream>

int main()
{
//-------------------vvvvvv---------------> not withing quotes
        std::cout << _TEST_ << std::endl;
}

The output of the above modified program is:上面修改后的程序的output为:

test

Demo演示

Explanation解释

In the modified program, the macro _TEST_ stands for the string literal "test" .在修改后的程序中,宏_TEST_代表字符串文字"test" And thus when we use that macro in the statement std::cout << _TEST_ << std::endl;因此,当我们在语句std::cout << _TEST_ << std::endl;中使用该宏时, it will be replaced by the string literal, producing the expected output. ,它将被字符串文字替换,产生预期的 output。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM