This is a question that popped into my head when I had to write a program that included multiple variables that each stored a single digit of a number. Let's say I declared several variables in main (or some other function):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n_1 = 1;
int n_2 = 2;
int n_3 = 3;
int n_4 = 4;
int n_5 = 5;
/*
More variables
.
.
.
followed by multiple printf()s
*/
exit(EXIT_SUCCESS);
}
Assume due to some unfortunate circumstances that I need all those separate variables and I cannot use an array or use a different, more efficient solution.
If I wanted to print the value stored in each variable, I could of course just print each single variable with a separate call to printf() or a single long call to printf(). But could I achieve the same goal more efficiently. I am especially interested if it is possible to do this in a loop. A solution which is common in scripting languages is using the value of the iterator variable in a for loop to complete the name of the variable given that the name has a fixed structure as in:
for (int i; i < n; ++i) {
printf("%d\n", n_i);
}
but this will obviously not work in C (and I know why so no need to point this out). So what is the take on this by experienced people?