如何根据循环索引访问任何变量名称 [英] How to access any variable name according to loop index

查看:173
本文介绍了如何根据循环索引访问任何变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些整型变量,我将它们命名为 N0 N9 。我想用一个循环来访问它们。我想这code要做到这一点:

I have some integer variables, I named them n0 to n9. I want to access them using a loop. I tried this code to do that:

int n0 = 0, n1 = 0, n2 = 0, n3 = 0, n4 = 0; 
int n5 = 0, n6 = 0, n7 = 0, n8 = 0, n9 = 0;    

for(i = 0; i < 10; i++){
    if(digit == 1){
        n[i] = n[i] + 1;
    }               
}

我知道这是不正确的做法,但我不知道该怎么做是正确的。

I know it's not the right way, but I don't know how to do it correctly.

推荐答案

答案很简单:声明一个数组来代替,如 INT N [10]

Simple answer: declare an array instead, as int n[10].

高级 - 答:这似乎并不在这里是如此,但在你需要使用数组项单独的变量名,不管出于什么原因的情况下,你可以使用一个联盟:

Advanced answer: it doesn't seem to be the case here, but in the case where you do need to use individual variable names of array items, for whatever reason, you can use an union:

typedef union
{
  struct
  {
    int n0;
    int n1;
    int n2;
    ... // and so on
    int n9;
  };

  int array[10];

} my_array_t;

如果你有一个古老的恐龙编译器,然后用声明一个变量名的结构,如结构{...}等;

如何在实际的,现实世界的程序中使用上述类型:

How to use the above type in a practical, real world program:

  my_array_t arr = {0};

  for(int i=0; i<10; i++)
  {
    arr.array[i] = i + 1;
  }

  // access array items by name:    
  printf("n0 %d\n", arr.n0); // prints n0 1
  printf("n1 %d\n", arr.n1); // prints n1 2


或者,你可以通过名字初始化成员:


Or you could initialize members by name:

  my_array_t arr = 
  { 
    .n0 = 1, 
    .n1 = 2,
    ...
  };


傻,如何使用上述类型分配值变量,而无需使用数组符号人为的例子:


Silly, artificial example of how to use the above type to assign values to the variables without using array notation:

  my_array_t arr = {0};

  // BAD CODE, do not do things like this in the real world:

  // we can't use int* because that would violate the aliasing rule, therefore:
  char* dodge_strict_aliasing = (void*)&arr;

  // ensure no struct padding:
  static_assert(sizeof(my_array_t) == sizeof(int[10]), "bleh");

  for(int i=0; i<10; i++)
  {
    *((int*)dodge_strict_aliasing) = i + 1;
    dodge_strict_aliasing += sizeof(int);
  }

  printf("n0 %d\n", arr.n0); // prints n0 1
  printf("n1 %d\n", arr.n1); // prints n1 2

  for(int i=0; i<10; i++)
  {
    printf("%d ",arr.array[i]); // prints 1 2 3 4 5 6 7 8 9 10
  }

这篇关于如何根据循环索引访问任何变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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