【问题标题】:What does # operator do in C++ macros? [duplicate]# 运算符在 C++ 宏中的作用是什么? [复制]
【发布时间】:2021-10-20 19:44:13
【问题描述】:

我遇到了这个宏:

#define STR_ERROR(ecode) case ecode: return #ecode;

#ecode 部分有什么作用?

ecode 是一个 int,这个函数返回一个 const char*。

我确定这个问题已经得到解答,但是我的 search-foo 已经抛弃了我。 ecode 本身特定于此代码。搜索 c++ # 可以提供有关宏的一般信息(以及一些与 C++ 相关的编号列表)。

【问题讨论】:

  • 如果可能请添加源代码。
  • 它将参数字符串化。例如。 STR_ERROR(1) 扩展为 case 1: return "1";
  • 我的 search-foo 抛弃了我 - c++ macro what does single hash do

标签: c++ macros


【解决方案1】:

根据cppreference

# 运算符在替换列表中的标识符之前通过参数替换运行标识符并将结果括在引号中,有效地创建字符串文字

来自Microsoft Docs的示例

#include <stdio.h>
#define stringer( x ) printf_s( #x "\n" )
int main() {
   stringer( In quotes in the printf function call );
   stringer( "In quotes when printed to the screen" );
   stringer( "This: \"  prints an escaped double quote" );
}

结果:

In quotes in the printf function call
"In quotes when printed to the screen"
"This: \"  prints an escaped double quote"

Google-Fu 提示:我刚刚搜索了C++ macro #,Google 建议在最后添加operator,这些文档在第一页。

【讨论】:

  • 这不是微软编译器特有的东西。这是指向编译器独立页面的链接:en.cppreference.com/w/cpp/preprocessor/…
  • 谢谢。我尝试了您建议的搜索,并没有建议添加“操作员”。有一个与 c macro stringify 相关的搜索,我不认为它有任何相关性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-06
  • 2017-04-24
  • 1970-01-01
  • 2015-10-15
  • 2011-04-18
  • 2021-03-28
  • 2014-01-15
相关资源
最近更新 更多