简体   繁体   中英

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!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM