且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C 中获取变量名的编程方式?

更新时间:2023-01-19 11:47:37

你可以试试这样的:

#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.