Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a for loop to change a variable name in C?

This is a generic question, so there is no actual code that I am trying to troubleshoot. But what I want to know is, can I use a for loop to change the name of a variable in C? For instance, if I have part1, part2, part3, part..., as my variable names; is there a way to attach it to my loop counter so that it will increment with each passing? I toyed around with some things, nothing seemed to work.

like image 266
Jason Golightly Avatar asked Oct 27 '25 10:10

Jason Golightly


1 Answers

In C, you can't 'change the name of the loop variable' but your loop variable does not have to be determined at compile time as a single variable.

For instance, there is no reason in C why you can't do this:

int i[10];
int j;

j = /* something */;

for (i[j] = 0 ; i[j] < 123 ; i[j]++)
{
    ...
}

or event supply a pointer

void
somefunc f(int *i)
{
    for (*i = 0; *i<10; *i++)
    {
        ...
    }
}

It's not obvious why you want to do this, which means it's hard to post more useful examples, but here's an example that uses recursion to iterate a definable number of levels deep and pass the innermost function all the counter variables:

void
recurse (int levels, int level, int max, int *counters)
{
    if (level < levels)
    {
        for (counters[level] = 0;
             counters[level] < max;
             counters[level]++)
        {
            recurse (levels, level+1, max, counters);
        }
        return;
    }

    /* compute something using counters[0] .. counters[levels-1] */
    /* each of which will have a value 0 .. max */
}

Also note that in C, there is really no such thing as a loop variable. In a for statement, the form is:

for ( A ; B ; C ) BODY

Expression A gets evaluated once at the start. Expression B is evaluated prior to each execution of BODY and the loop statement will terminate (and not execute BODY) if it evaluates to 0. Expression C is evaluated after each execution of BODY. So you can if you like write:

int a;
int b = /* something */;
int c = /* something */;
for ( a=0; b<5 ; c++ ) { ... }

though it will not usually be a good idea.

like image 114
abligh Avatar answered Oct 28 '25 23:10

abligh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!