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
The right way to do it is to declare an integer array and not 10 different variables:
int n[10];
Now you can access 10 int variables with n[0]
through n[9]
.
It is barely not possible to access your variables just like you want to, without any array.
All that comes to my mind, is to consider 10 separate cases for each variable, so:
int i;
int n0, n2, n3 ... n9;
for(i=0; i<10; i++)
{
switch(i)
{
case 0: n0++; break;
case 1: ...
}
}
int n[10] = {0};
/*or you can initilize like this also , this will make all the elements 0 in array*/
for(i = 0; i < 10; i++){
if(digit == 1){
n[i] = n[i] + 1;
}
}
Try this and let me know
Since you can't use "real" arrays, lets use some dynamic memory instead (really silly but ...):
#define NUMVALS 10
int main(int argc, char *argv[])
{
int *values, *ptr, i;
ptr = values = malloc(sizeof(int) * NUMVALS);
for (i = 0; i < NUMVALS; i++) {
ptr++ = 0; /* Set the values here or do what you want */
/* Ofc values[i] would work but looks like array access... */
}
...
}
If you really have several variables that you want to access like you say, well save the pointers to them in an array (or like above) and access them that way, but it's still not by name. If you must access them by name well I think you're left with the pre-processor. I don't know of any other proper way to do it.
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;
In case you have an old dinosaur compiler, then declare the struct with a variable name such as struct { ... } s;
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
}