如何在C ++中打印变量的名称? [英] How to print a variable's name in C++?

查看:645
本文介绍了如何在C ++中打印变量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在C中获取变量名的程序化方法

我已经检查了一些博客,在这里发布之前。我试过下面的代码片段...

I have checked some of the blogs before posting this here. I have tried the following snippet...

int a=21;

int main()
{
   cout<<#a<<a<<endl;
   return 0;
}

我在ubuntu 10.04上使用g ++编译器。我得到以下错误:

I am using g++ compiler on ubuntu 10.04. And I am getting the following error:

sample.cpp:17: error: stray ‘#’ in program. 

请建议我如何打印变量名称。

Please suggest me how to print the variables name .

推荐答案

字符串化宏只适用于宏。

The # stringifying macro thing only works inside macros.

您可以这样做:

#include <iostream>

#define VNAME(x) #x
#define VDUMP(x) std::cout << #x << " " << x << std::endl

int main()
{
  int i = 0;
  std::cout << VNAME(i) << " " << i << std::endl;

  VDUMP(i);

  return 0;
}

这篇关于如何在C ++中打印变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆