for loop on different variables names

后端 未结 4 781
野趣味
野趣味 2021-01-27 12:09

I am programing for a while but for this i couldn\'t find an answer yet .

lets say i want to run on a loop when i change the names of the variables.

lets say i h

相关标签:
4条回答
  • 2021-01-27 12:37

    If you absolutely have to keep these variables separate, then the only option you have is to "index" your variables by using an array of pointers and access your variables through it

    int ran1, ran2, ran3;
    
    int *rans[3] = { &ran1, &ran2, &ran3 };
    
    for (int k = 0; k < 3; k++)
      *rans[k] = k;
    

    (But maybe you should have used an int array instead of three separate variables from the very beginning.)

    0 讨论(0)
  • 2021-01-27 12:38

    You can simple achieve this with defining an array as int ran[3] and then writing below code to get it:-

    ran[k % 3] = k;
    
    0 讨论(0)
  • 2021-01-27 12:43

    Make it an array! Using different names differentiated by a number is a bad practice:

    int ran[3];
    
    for (int k = 0; k < 3; k++)
    {
        ran[k % 3] = k;
    }
    

    Now, instead of using ran1, or ran2, you would use ran[1] or ran[2]. Arrays in C are quite confusing, and they are distinct from pointers.

    0 讨论(0)
  • 2021-01-27 12:52

    uses arrays:

    int ran[3];
    for(int k=0;k<3;k++)
     ran[k]=k; 
    
    0 讨论(0)
提交回复
热议问题