c语言中如何返回一个变量名并赋值返回的变量的值 [英] How to return a variable name and assign the value of the variable returned in c

查看:42
本文介绍了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,它应该返回变量名(如 "aVar", "bVar"> 或 "cVar").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?

推荐答案

这里的简单答案是这在 C 中是不可能的.

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天全站免登陆