MOON
MOON

Reputation: 2801

Why doesn't this array become zero?

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};

Upvotes: 0

Views: 118

Answers (3)

MBZ
MBZ

Reputation: 27592

The Array is statics. static variables only initialize once. Therefor, Array becomes zero only on the first call.

if you remove the static keyword it will become zero on every call.

by the way the following code is very strange:

for(int j = i; j <=i ; j++)

because it only runs for j=i. So you can change the whole function by the following:

double function(int i)
{
    static int Array[5] = {0};
    Array[i+1] = Array[i]+1;
    return Array[i+1];
}

Upvotes: 1

Alok Save
Alok Save

Reputation: 206518

When you use static keyword for declaring a variable inside a function. Then:

  • The variable is created when the function is called first time.
  • Thereafter the variable remains alive throughout the lifetime of the program &
  • The value of the variable persists between function calls.

What you observe is this property of the keyword static at work.

Upvotes: 3

Jon
Jon

Reputation: 437346

The array is static, which means it gets initialized just once (the first time function is called). It keeps its existing items thereafter. If you remove the static keyword you will get 1, 1, 1, 1, 1 instead.

By the way, the for loop inside function is redundant (it's guaranteed to only execute exactly once).

Upvotes: 5

Related Questions