3

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.

abligh
  • 24,573
  • 4
  • 47
  • 84
Jason Golightly
  • 71
  • 1
  • 1
  • 7
  • 3
    Can't you use an array instead? – user2682768 Mar 22 '15 at 15:05
  • As this is highly dependent of the language you are using, please add an appropriate tag. – O. R. Mapper Mar 22 '15 at 15:05
  • Sorry, the language I am using is C. @user2682768. Yes, I can use an array, I was just wondering if this was possible. – Jason Golightly Mar 22 '15 at 15:08
  • Read chapter 2 - Loops in C – Ed Heal Mar 22 '15 at 15:13
  • I misread your question the first time, thinking that you were having trouble assigning values to a variable in a loop. If that is the case, you need to read up on scope. If you want to actually define variables, which is something I’ve wanted to do in iOS, you can’t. There are some languages, like SAS, that have a macro preprocessor that will allow you to do that. however, C-based languages don’t allow you to do it. As a previous commenter noted, in your case an array would be better anyway. – JScarry Mar 22 '15 at 15:25
  • 2
    @JScarry Much as some would like you to forget it, C does *have* a macro system that would be capable of that, although it's not worth adding as an answer since it'd cause more confusion than good. – Alex Celeste Mar 22 '15 at 16:13
  • 1
    A [Homoiconic](https://en.wikipedia.org/wiki/Homoiconicity) language like Lisp or Rebol can do all kinds of things in terms of "automating the process of programming itself" (and not with "macros" or string-based "eval" like JavaScript). If you're curious about writing code that spontaneously generates code via iteration and runs it...then by all means investigate that stuff! It's not a bad question, it's just that C is a different beast, with a different history and domain of application...and trying to bend it that way is generally an abuse. – HostileFork says dont trust SE Mar 22 '15 at 16:26
  • 1
    Maybe you could try to explain better what you want to do. As you can in the comments to my post below, your post is unclear. Better questions -> better answers. Fo rexample, post what you toyed around with and which errors you got. That might explain what you are trying. – Peter - Reinstate Monica Mar 22 '15 at 19:05

3 Answers3

3

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.

abligh
  • 24,573
  • 4
  • 47
  • 84
2

The answer is, as @user2682768 correctly remarked, an array. I am not sure whether you are aware of that and consciously do not want to use an array for some reason; your little experience doesn't give me enough information. If so, please bear with me.

But you'll recognize the structural similarity between part1, part2, part3... and part[1], part[2], part[3]. The difference is that the subscript of an array is variable and can be changed programmatically, while the subscript part of a variable name cannot because it is burned in at compile time. (Using macros introduces a meta compiling stage which lets you programmatically change the source before actually compiling it, but that's a different matter.)

So let's compare code. Say you want to store the square of a value in a variable whose name has the value as a suffix. You would like to do something like

int square1, square2, square3;
int i;
for(i=1; i<=3; i++)
{
   square/i/ = i*i; /* /i/ to be replaced by suffix "i".
}

With arrays, that changes to

int square[4];
int i;
for(i=1; i<=3; i++)
{  
   /* the (value of) i is now used as an index in the array.*/
   square[i] = i*i; 
}

Your idea to change the variable name programmatically implies that all variables have the same type (because they would have to work in the same piece of code, like in my example). This requirement makes them ideally suited for array elements which all have to be of the same type. If that is too restrictive, you need to do something fancier, like using unions (but how do you know what's in it at any given moment? It's almost as if you had different variables to begin with), void pointers to untyped storage or C++ with templates.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
  • I think OP wants to suffix the loop variable, not suffix the thing done in the loop; though it's not fantastically clear. – abligh Mar 22 '15 at 16:46
  • @abligh In all reality, we do not know what he wanted ;-). But "to attach it [the suffixed variable] to my loop counter" seems to indicate to me that these two are distinct. – Peter - Reinstate Monica Mar 22 '15 at 16:48
  • Indeed we don't. I'd read that very sentence to mean that he wanted the loop counter itself to be suffixed (attached) by something, hence my answer. But I can see your interpretation too, so +1. – abligh Mar 22 '15 at 16:51
  • @abligh Ah, now I understand. Yes, possible, too. – Peter - Reinstate Monica Mar 22 '15 at 19:15
0

In C You cannot append to a variable name an expression that expands to a number and use it as a sort of suffix to access different variables that begin in the same way.

The closest you can get, is to "emulate" this behaviour using a switch construct, but there wouldn't be much of a point to try to do this.

What you asked for is more suited to scripting languages.

Mariano Macchi
  • 242
  • 1
  • 7