2

I have a bunch of variables named index1, index2, ..., indexn. I want to calculate i = array[index1] + array[index2] + ... + array[indexn]. I heard that I can do that in a loop, getting the current variable name from the loop index. How can I do that?

1
  • 3
    Having a bunch of numbered variables is clue #1 that there's something wrong with your program's structure. Why aren't they in an array or other appropriate compound object? Commented Jul 2, 2010 at 10:33

2 Answers 2

4

Instead of having individual variables like this:

int index1, index2, index3, ...indexN:

you should consider using an array of indices:

int index[N];

and then you can sum in a loop, e.g.

sum = 0;
for (i = 0; i < N; ++i)
{
    sum += array[index[i]];
}
Sign up to request clarification or add additional context in comments.

Comments

0

Sorry, this is not possible in objective-c. It works for example in php.

There are ways to get objects by name if your data model allows for this, but in general variable names cannot be synthesized by name.

1 Comment

This works only if you are using key value coding (KVC) to hold your variables. I think they are just plain ints in your code and not KVC compliant properties. May think about refactoring them into an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.