是否有可能使用一个for循环用C来改变一个变量的名字吗? [英] Is it possible to use a for loop to change a variable name in C?

查看:445
本文介绍了是否有可能使用一个for循环用C来改变一个变量的名字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个通用的问题,所以,我尝试解决任何实际的code。但我想知道的是,我可以使用循环改变在C变量的名称?举例来说,如果我有第1部分第2部分第3部分部分... ,因为我的变量名;有没有办法把它连接到我的循环计数器,这样它会每过增加?我玩弄与周围的一些事情,似乎没有什么工作。

This is a generic question, so there is no actual code that I am trying to troubleshoot. But what I want to know is, can I use a for loop to change the name of a variable in C? For instance, if I have part1, part2, part3, part..., as my variable names; is there a way to attach it to my loop counter so that it will increment with each passing? I toyed around with some things, nothing seemed to work.

推荐答案

答案是,正如@ user2682768正确地说,一个数组。我不知道你是否意识到这一点,并自觉不希望使用某种原因,数组;你的小经验并没有给我足够的信息。如果是的话,请多多包涵。

The answer is, as @user2682768 correctly remarked, an array. I am not sure whether you are aware of that and consciously do not want to use an array for some reason; your little experience doesn't give me enough information. If so, please bear with me.

但你会认识到第1部分第2部分之间的结构相似,第三部分 ...和部分[1] 部分[2] 部分[3] 。不同的是,数组的下标是可变的,可以通过编程来改变,而可变的部分标名称的不能因为它是在编译时烧毁英寸(使用宏介绍了元编译阶段,它可以让你以编程方式更改的的其实之前编译它,但是这是一个不同的问题。)

But you'll recognize the structural similarity between part1, part2, part3... and part[1], part[2], part[3]. The difference is that the subscript of an array is variable and can be changed programmatically, while the subscript part of a variable name cannot because it is burned in at compile time. (Using macros introduces a meta compiling stage which lets you programmatically change the source before actually compiling it, but that's a different matter.)

所以,让我们比较code。说你要一个值的平方存储在其名称具有值作为后缀的变量。你会喜欢做这样的事情。

So let's compare code. Say you want to store the square of a value in a variable whose name has the value as a suffix. You would like to do something like

int square1, square2, square3;
int i;
for(i=1; i<=3; i++)
{
   square/i/ = i*i; /* /i/ to be replaced by suffix "i".
}

使用数组,即变为

int square[4];
int i;
for(i=1; i<=3; i++)
{  
   /* the (value of) i is now used as an index in the array.*/
   square[i] = i*i; 
}

您的想法改变变量名编程意味着所有的变量具有相同类型的(因为他们将不得不在同一块code在我的示例工作,等等)。此要求使它们非常适合用于数组元素这都必须是同一类型的。如果太严格,你需要做一些票友,喜欢用工会(但你怎么知道它在任何时候有什么不?这是几乎一样,如果你有不同的变量开始),空指针类型化存储或C ++使用模板。

Your idea to change the variable name programmatically implies that all variables have the same type (because they would have to work in the same piece of code, like in my example). This requirement makes them ideally suited for array elements which all have to be of the same type. If that is too restrictive, you need to do something fancier, like using unions (but how do you know what's in it at any given moment? It's almost as if you had different variables to begin with), void pointers to untyped storage or C++ with templates.

这篇关于是否有可能使用一个for循环用C来改变一个变量的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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