Static and Local Scope

Source: Internet
Author: User

Someone says, "I just want to define a int var in a. h file. Who PA?

Now we see the following example.

Static:local in You

---------------ah.h-----------------

static int a=1;

------------------------------

----------------Callseta.cpp--------------

#include "ah.h"

#include <iostream>

using namespace Std;

void Seta ()

{

a=2;

cout<< "Call Seta ()" <<endl;

cout<< "in Call, A=" <<a<<endl;

}

--------------------------------------------

-----------------main.cpp---------------

#include "ah.h"

#include <iostream>

extern void Seta ();

using namespace Std;

void Main ()

{

cout<< "A=" <<a<<endl;

Seta ();

cout<< "After Seta ()" <<endl;

cout<< "A=" <<a<<endl;

}

-----------------------------------

Output:

A=1
Call Seta ()
In Call, a=2
After Seta ()
A=1
Please press any key to continue ...

----------------------------------

This is the local in main.cpp. For include "", the A is static.

So there is "int a", one in Main.cpp's scope or workspace, the other in Callseta.cpp ' s scope.

They is, different int Var, with different address allocated.

They only live in their own. Any of the guy outside can isn't see her beauty.

Interesting things is:

When your call Seta () is main.cpp, the pointer turns to the program space of Callseta.cpp.

It isn't realized that firstly clone of the program to the MAIN.CPP's program data segament.

The pointer turns onto the orginal and the only one program data segament of Seta () in Callseta.cpp.

So in this scope, a means his A, not the A in main, and which is amazing.

Static and Local Scope

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.