如何返回一个变量名,并分配在C返回的变量的值 [英] How to return a variable name and assign the value of the variable returned in c

查看:215
本文介绍了如何返回一个变量名,并分配在C返回的变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个动态的变量,其值在运行时会有所不同。

I want to use a dynamic variable whose value will vary during the run time.

例如

char * aVar = "ABC";
char * bVar = "DEF";
char * cVar = "XYZ";

char *dVar = NULL;

dVar = foo1();

print dVar;

foo1 内部调用 foo2的,它应该会返回变量名称(如阿瓦尔BVARCVaR的)。 foo1 应该返回为根据 foo2的的返回值命名该变量的值。

foo1 internally calls foo2, which should return the variable names (like "aVar", "bVar" or "cVar"). foo1 should return the value of said variable as named according to foo2's return value.

让我们可以使用变量名(非标)宏:

to get the variable name we can use (non-standard) macro:

##define GET_VAR(varname) #varname; 

...但我怎么能得到命名变量的值?

... but how am I able get the value of the variable named?

推荐答案

在这里简单的回答是,这是不可能的温度。

The simple answer here is that this is not possible in C.

较长的答案是,这需要一种语言,这恐怕是一般只出现在脚本语言如Python自省和动态特性。即使有做这样的事情是不鼓励的。

The longer answer is that this requires introspection and dynamic features in a language, which is something that is generally only seen in scripting languages such as Python. And even there doing something like this is not encouraged.

我建议你重新考虑你正在努力解决,并检查是否有可能不是一个更好的方法来接近它的问题。也许使用数组,映射或哈希表可能是一种替代方法,为你工作。

I suggest that you reconsider the problem you are trying to solve and check if there might not be a better method to approach it. Perhaps using an array, map or hash table might be an alternative approach that works for you.

这篇关于如何返回一个变量名,并分配在C返回的变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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