Scope, lifetime, and visibility of C + + variables

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.