0

Say I want to do something like this to increment a int array every time I call f():

void f()
{
  static int v[100]={1,2,3...100};
  for (int i=0; i<100; i++) v[i]++;
}

i.e. I want:

first call f(): v[100]={1,2,3...100};
second call f(): v[100]={2,3,4...101};
...

apparently the following will not do it:

void f()
{
  static int v[100]; for (int i=0; i<100; i++) v[i]=i+1;
  for (int i=0; i<100; i++) v[i]++;
}

Not sure how to achieve it. Thanks!

2
  • Isn't the problem that, you're (re)setting the array to a constant value with the first for loop before you increment it with the second? Commented Mar 2, 2013 at 4:06
  • Why not generate the code from a script. Hell just use Excel and create a sheet and save it as CSV. Bit of favourite IDE on the side it will slot in. Commented Mar 2, 2013 at 4:12

3 Answers 3

2

The static array declared inside the function can only be referenced inside it, and it exists as long as the program runs. It can be initialized as you hint in your first version.

The second version first fills the array with values and then increments them, each time the function is called. Presumably not what you want.

Either split the initializing and incrementing into two functions, defining the static array outside both, or just fill the array in by hand like your first version (could even write a program to generate the part initializing the array into a file, and then copy that into your source). The filling in of the array in this case is done by the compiler, there is no runtime penalty.

Sign up to request clarification or add additional context in comments.

3 Comments

Splitting them is not an option for me. Could you give me a script to do it at compilation stage?
Your first version does exactly that, I assume that this is just a mockup of a much more complex situation (with more than a 100 elements in the array).
@HailiangZhang Why not track a flag value for the first call to f(), and use some conditional logic to choose between which for loop to use? Also, what is the purpose of these (seemingly silly) restrictions?
1

you may do this with another static variable which holds the mark or starting point for your array. say

{
    static int fst = 0,
        v[MAXSIZE] = {0};    //#define MAXSIZE 100
        fst++;
        for(int i = 0; i < (MAXSIZE+fst-1); i++) v[i] = i + fst;
}

Comments

0

You can't initialize your static array like that. That first for loop in your second code block will just get called every time f is called.

You could initialize the static v variable to NULL instead, and then before the for loop that actually increments the array elements, check for NULL and initialize with i+1 if necessary.

Comments

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.