简体   繁体   中英

The scope and lifetime of static local variable in c++

#include<iostream>
using namespace std;

int &fun()
{
    static int x = 10;
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}

when the above program is run,the output is 30.The integer variable x was returned,as a reference to the main() function and it is assigned the value of 30.But isn't the scope of x limited to the fun() function?;If so,why are we able to change the value of it in main function??

Scope is limited means any attempt to access x directly outside the scope is forbidden.

Within a scope, unqualified name lookup can be used to associate the name with its declaration.

But you can always return a pointer or reference to this variable if variable is alive and you change it through that reference or pointer which points to the same variable. The name of this reference may be anonymous (temporary) or may be bound to some named reference.

About lifetime, it starts when the function containing static variable is called first time and ends when the program end.

Indeed the scope of x is limited to fun() .

But because that function returns a reference to x , the caller (ie main ) is able to modify x through that reference. That's what's happening here: x is set to 10 the first time the function is entered, but is changed to 30 by the assignment fun() = 30 .

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