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
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
}