I have written this piece of code:
#include <iostream>
using namespace std;
double function(int i)
{
static int Array[5] = {0};
for(int j = i ; j <= i ; j++)
{
Array[j+1] = Array[j]+1;
}
return Array[i+1];
}
int main()
{
for(int i = 0 ; i <= 4 ; i++)
{
cout << function(i) << endl;
}
return 0;
}
Which outputs 1,2,3,4,5
I am wondering why elements of Array at each call of function(i) doesn’t become zero despite this piece of code :
static int Array[5] = {0};
The array is
static, which means it gets initialized just once (the first timefunctionis called). It keeps its existing items thereafter. If you remove thestatickeyword you will get 1, 1, 1, 1, 1 instead.By the way, the
forloop insidefunctionis redundant (it’s guaranteed to only execute exactly once).