Reputation: 18870
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!
Upvotes: 0
Views: 593
Reputation: 2176
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;
}
Upvotes: 1
Reputation: 11791
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.
Upvotes: 2
Reputation: 19153
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.
Upvotes: 0