在 C 中获取变量名的编程方式? [英] Programmatic way to get variable name in C?

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

问题描述

我正在开发一个工具来从变量中转储数据.我需要转储变量名和值.

I am developing a tool to dump data from variables. I need to dump the variable name, and also the values.

我的解决方案:将变量名存储为字符串,并打印变量名",然后是其值.

My solution: Store variable name as a string, and print the "variable name", followed by its value.

有没有什么程序化的方式来知道变量名?

Is there any programmatic way to know the variable name?

推荐答案

你可以试试这样的:

#define DUMP(varname) fprintf(stderr, "%s = %x", #varname, varname);

我曾经使用这个标题我写过,当我刚接触 C 时,它可能包含一些有用的想法.例如,这将允许您打印 C 值并在其中提供格式说明符(以及一些附加信息):

I used to use this header I wrote, when I was new to C, it might contain some useful ideas. For example this would allow you to print a C value and provide the format specifier in one (as well as some additional information):

#define TRACE(fmt, var) 
        (error_at_line(0, 0, __FILE__, __LINE__, "%s : " fmt, #var, var))

如果您使用 C++,您可以使用传递值的类型并适当地输出它.如果是这种情况,我可以提供一个更有利可图的示例,说明如何漂亮地打印"变量值.

If you're using C++, you could use the type of the passed value and output it appropriately. I can provide a much more lucrative example for how to "pretty print" variable values if this is the case.

这篇关于在 C 中获取变量名的编程方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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