user11067275
user11067275

Reputation: 99

Initialization of a local static variable throught multiple function calls

int f(int &g){
    static int a=g;
    a+=1;
    return a;
}

int main()
{
    int g=0;
    int a=f(g);
    g=10;
    a=f(g);
    cout<<a;
    return 0;
}

The above code gives output 2. What my guess was that it should be 11.

I do understand that the a in main function is not the same as that in f function. So when g=0, a in f would be 1, I believe. Then when g=10, it should be 11, giving a=11 in main. Why isn't that the case? Thanks!

Upvotes: 1

Views: 366

Answers (1)

lubgr
lubgr

Reputation: 38287

You are misinterpreting the static keyword here. When a local variable is declared static, it is initialized once. Inside of the function, this is when then function is called the first time. You first call this function in

int g=0;
int a=f(g);

The local variable a inside f is hence initialized to zero and then incremented. Later on, you call f a second time,

g=10;
a=f(g);

but as the local variable is already initialized, it is not overwritten. Instead, the second increment takes place, resulting in the value of 2.

Upvotes: 1

Related Questions