Local variables
Scope: A variable defined within a function that is scoped to the body of the function.
Lifetime: The program executes to this function to assign a memory unit to a local variable, and the storage unit that the local variable occupies is freed after the function executes
Global variables
Variables defined outside the body of the function are global variables that can be used by all other functions in this file.
Scope: All files. In a CPP-defined global variable used in another CPP, the extern description should be inside or outside the function body that uses it
Lifetime: A global variable occupies a fixed memory unit during the execution of a program, and the lifetime is the entire program running.
Experiment Code
Scope, lifetime, and visibility of/** variables * date:2015-07-13* author:zhang*/#include <iostream>using namespace std;void fn1 (); int x = 1;int y = 2;int main () {int x = 10;int y = 20;cout << "x =" << x << ", y =" << y << endl;fn1 (); Co UT << "x =" << x << ", y =" << y << endl;return 0;} void Fn1 () {int y = 100;cout << "x =" << x << ", y =" << y << Endl;}
Operation Result:
x = 10,y = 20x = 1,y =100x = 10,y = 20
From the running result, when the local variable has the same name as the global variable, the global variable is hidden within the scope of the local variable.
Other articles that you can refer to:
Http://www.jb51.net/article/41324.htm
http://my.oschina.net/hnuweiwei/blog/261070
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Scope, lifetime, and visibility of C + + variables