Storage Allocation and scope of Variables

Source: Internet
Author: User
Tags implement definition microsoft c

1. Data and Storage types of Variables

In C, each variable has two attributes: Data Type and storage type.Data TypeThat is, the generic, integer, and floating point types;Storage TypeIt refers to the storage mode of variables in the memory. It determines the scope and lifetime of the variables.

There are four Storage types of variables: auto (automatic), register (register), extern (external), and static (static ). Auto and register are used to declareInternalThe auto variable is stored inStackThe register variable is stored inRegister. Static is used to declare local variables, and extern is used to declare global variables.

The general form of variable Declaration: <Storage Type> <Data Type> <Variable name list>

If the storage type is not specified when variables are declared, the storage type of internal variables is auto by default, and the storage type of external variables is extern by default.

There are two ways to declare external variables: Definition declaration and reference declaration.

Definition DeclarationIsCreateVariable.Reference DeclarationIt is used to establish the relationship between variables and memory units.LinkIndicates that the variable to be referenced has been declared as defined elsewhere in the program source file. The definition Declaration can only be placed outside the function, while the reference declaration can be placed outside the function or inside the function.

Extern int B; // The reference declaration, which can also be placed in function fun void fun () {printf ("d %", B); // output} extern int B = 5; // definition declaration. The keyword extern can be omitted.

2. Scope of Variables

The scope of a variable refers to a range fromCode SpaceIt determinesVisibilityWhich indicates the region in which the variable is available, that is, the lines of code in the program that can use the variable. There are three scopes: local scope, global scope, and file scope, which correspond to local variables, global variables, and static variables ).

2.1 local variables

Most variables have local scopes and are declared inside the function (including the main function). Therefore, local variables are also calledInternal Variable. Variables declared in the statement BlockValid only within the statement BlockIs also a local variable. The scope of a local variable starts at the declared position of the variable and ends at the right curly braces that indicate the end Of the function or block. Function parameters also have local scopes. For more information, see C function call practices under x86.

#include <iostream> using namespace std;int main(){int x = 0;{int x=1;cout << x << endl;{cout << x << endl;int x = 2; // "x = 1" lost its scope here covered by "x = 2"cout << x << endl; // x = 2// local variable "x = 2" lost its scope here}cout << x << endl; // x = 1// local variable "x = 1" lost its scope here}cout << x << endl;// local variable "x = 0" lost its scope herereturn 0;}

Local Summary:

Local variables are valid only within the block range. "Block" includes user-defined {} and functions, including temporary (automatic) variables in {}, function parameters, and function bodies) variable.

Test ()-> GetMemory ():

Invalid void GetMemory1 (char * p) {p = (char *) malloc (100);/* parameter pointer Variable _ p value changed */} void Test1 (void) {char * str = NULL; GetMemory1 (str);/* The str value of the real parameter pointer variable is still NULL */strcpy (str, "hello world "); /* program crash due to illegal memory access */printf (str);} -------------------------------------------------------------- char * GetMemory2 (void) {char * p = "hello world "; /* The Pointer Points to the static Constant Area (. rodata), cannot modify */return p;} void Test2 (void) {char * str = NULL; str = GetMemory2 (); printf (str ); /* allow read-only access */} using char * GetMemory3 (void) {char p [] = "hello world";/* pointer p is the automatic stack variable */return p ;} /* stack automatic variables will be released here */void Test3 (void) {char * str = NULL; str = GetMemory3 ();/* str non-NULL, however, the stack zone variables may be cleared */printf (str);/* may be garbled */}--------------------------------------------------------------

2.2 global variables and extern keywords

The following are MSDN explanations of the extern keyword in C/C ++:

The externStorage-Class Specifier (C)

Avariable declared with the extern storage-class specifier isReferenceTo a variable with the same namedefined at the externallevel in any of
Source files of the program.Internal externDeclaration is used to make the external-level variable definitionvisible within the block. Unless otherwisedeclared
At the external level, a variable declared with the extern keyword isvisible only in the block in which it is declared.

The externStorage-Class Specifier (C ++)

Theextern keyword declares a variable or function and specifies that it hasExternallinkage(Its name is visible from files other than the one in whichit's defined). When modifying
A variable, extern specifies that the variablehas static duration (it is allocated when the program begins and deallocatedwhen the program ends ).
The variable or functionmay be defined in another source file, orlaterin the same file. Declarations of variables and functionsat file scope are external by default.

(1) external variable reference Declaration

Global variables are declared outside the function, so they are also calledExternal variablesIts scope generally starts from the position of the variable declaration and ends at the end of the program source file. Global variables are most widely used, and can even act on all source files that make up the program. When multiple independently compiled source files are linked to a program, global variables or functions declared in a file can also be used in other linked files, however, an extern reference declaration must be made.

The keyword extern provides a method for declaring but not defining an object. In fact, it is similar to the function declaration,CommitmentThe object will be defined elsewhere: or elsewhere in this text file, or in other text files of the program.

If a function is to be used by functions in other files, the extern keyword is added during definition. If the extern and static keywords are not added, Some compilers generallyThe default value is extern.So you can call this function in other files. Therefore, extern is generally usedReference Declaration. However, some compilers and some large projects usually place the function definition in the source file without the extern, and put the function declaration in the header file, the explicit declaration is of the extern type. You only need to use the source file of this function to include this header file.

When using extern to declare global variables or functions, note that the declared variables or functions mustImplement definition in only one source file. If your program declares an external variable but does not define it in any source file, the program can be compiled, but cannot be linked through: Because the extern declaration will not cause memory allocation!

When a thread exists, special encoding must be performed to synchronize reading and writing operations on global objects by each thread.

(2) Specify the extern "C" link in C ++

As we all know, powerful and Complex C ++ features class, inheritance, virtual function mechanism, overload, and namespace, which make symbol management more complex. For example, C ++ Allows defining functions with different names in the parameter list: int func (int) and int fun (double ). How does the compiler differentiate these two functions during the linking process? To support the complex features of C ++, people have invented the mechanism of Name Decoration or Name Mangling to distinguish function symbols for overloading.

To be compatible with C, C ++ provides the extern "C" keyword in symbol management.Solve the name matching problemTo realize mixed programming between C ++ and C and other languages. The C ++ compiler treats the code in the braces modified by extern "C" as C code,Compile and link in C Language, The name modification mechanism of C ++ does not work.

If C ++ calls a. DLL written in C language, when it includes the header file of. DLL or the declared interface function, it should add extern "C "{}.

In C ++, when used with a string, externspecifies that the linkage conventions of another language are being used forthe declarator (s ). C functions and data can be accessed only if they arepreviously declared as having
C linkage. However, they must be defined in aseparately compiled translation unit.

Microsoft C ++ supports the strings "C" and "C ++" in the string-literal field. all of thestandard include files use the extern "C" syntax to allow therun-time library functions to be used in C ++ programs.

For example, to include a C-Language header file in a C ++ project:

Extern "C" {# include <stdio. h>}

The example project testExtern contains three files: C. c, CPP. cpp, and testExtern. cpp.

// C. C # include <stdio. h> int intc = 2010; void func () {printf ("func () \ n");} // CPP. CPP # include <stdio. h> extern int global;/* extern */INT intcpp = 2011;/* extern */const char * STR = "defined outside "; /* extern */INT intarray [3] = {2012,201 3, 2014}; static int staticintcpp = 2015; void funcpp () {printf ("funcpp ()-localstatic: % d, globalextern: % d \ n ", staticintcpp, global);} // testextern. CPP # include <stdio. H>/* extern */INT global = 2016; extern "C" Void func (); // C. implement/* extern */void funcpp () in C; // CPP. in CPP, the function declaration adds extern by default: Because only declaration is made here, it must be implemented elsewhere. // The following Code compiles the link extern "C" Void func1 () {printf ("func1 () \ n");} extern "C" {void func2 () in C mode () {printf ("func2 () \ n") ;}} extern "C" Void func3 (); // This file is implemented elsewhere (or in an external file, compile the link/* extern */void fun () according to the C method; // other places (or external files) in this file to implement extern "C" int intc; // C linkage specification in C ++ must be at global scopeint main () {printf ("intc = % d \ n", intc); extern int intcpp; // or put it before Main. If extern is removed, the local variable defined in main () is changed! Printf ("intcpp = % d \ n", intcpp); extern const char * STR; // or put it before Main. Printf ("str = % s \ n", STR); extern int intarray []; for (INT I = 0; I <3; I ++) {printf ("intarray [I] = % d \ n", intarray [I]);} // extern int staticintcpp; // error lnk2001 // printf ("staticintcpp = % d \ n", staticintcpp); func (); funcpp (); func1 (); func2 (); func3 (); fun (); Return 0;} void func3 () {printf ("func3 () \ n");} void fun () {printf ("Fun () \ n ");}

Extern Summary:

(1) extern supports calling (referencing) across source files within the project, as long as the symbolic definition can be found during the Link (including static link and dynamic.

(2) Use extern "C" in C ++ to specify compilation and link in C language (the name modification mechanism of C ++ does not work ).

2.3 static variables and static keywords

The following are MSDN explanations of the extern keyword in C/C ++:

Static (C ++)

The statickeyword can be used to declare variables, functions, class data members andclass functions.

Bydefault, an object or variable that is defined outside all blocks has staticduration and external linkage.Static durationMeans that the object orvariable isallocated
When the program starts andis deallocated when the program ends.External linkageMeans that thename of the variable is visible from outside the file in which the variable isdeclared. Conversely,Internal
Linkage
Means that the name is notvisible outside the file in which the variable is declared.

The statickeyword can be used in the following situations.

(1) Whenyou declare a variable or functionat file scope (global and/or namespace scope), the static keyword specifies that the variableor function has internal linkage. When you
Declare a variable, the variable hasstatic duration and the compilerinitializes it to0 unless you specify another value.

(2) Whenyou declare a variable in a function, the static keyword specifies that thevariableretains its state between callto thatfunction.

(3) Whenyou declare
Data member in a classdeclaration, the static keyword specifies that
One copy
Of the member is
Shared by all instances of the class. A staticdata member must be defined at file scope. An integral data member that youdeclare as const static can have an initializer.

(4) Whenyou declare
Member function in a classdeclaration, the static keyword specifies that the function isshared by all instances of the class. A staticmember function cannot access an instance member because the functiondoes
Not have an implicit this pointer. To accessan instance member, declare the function with a parameter that is an instancepointer or reference.

(5) Youcannot declare the members of a union as static. However, a globally declaredanonymous union must be explicitly declared static.

File Scope means that variables declared outside the function are only available within the current file range (including all defined functions in the file), but cannot be accessed by functions in other files. Generally, the static modifier is added before the declaration of variables or functions with file scopes.

Static variables can be global variables or local variables, but they all have a global life cycle, that is, they are terminated from the start of the program to the end of the program.

# Include <stdio. h> void fun () {static int a = 5; // static variable a is a local variable, but has a global survival period a ++; printf ("a = % d \ n", a) ;}int main () {int I; for (I = 0; I <2; I ++) fun (); getchar (); return 0 ;}

Output result:

A = 6

A = 7

The life cycle of the variable after the static operator is global, and its definition statement is static int a = 5; only run once, so when you call fun, this statement does not run. Therefore, the value of f is retained from the previous calculation, so it is 6, 7.

The following initWinsock routine uses the local static variable _ haveInitializedWinsock to ensure that Winsock is initialized only once.

int initWinsock(void){static int _haveInitializedWinsock = 0;WORD WinsockVer1 = MAKEWORD(1, 1);WORD WinsockVer2 = MAKEWORD(2, 2);WSADATAwsadata;if (!_haveInitializedWinsock){if (WSAStartup(WinsockVer1, &wsadata) && WSAStartup(WinsockVer2, &wsadata)){return 0; /* error in initialization */}if ((wsadata.wVersion != WinsockVer1)&& (wsadata.wVersion != WinsockVer2)) {WSACleanup();return 0; /* desired Winsock version was not available */}_haveInitializedWinsock = 1;}return 1;}

Functions in the same source program file can be called to each other, and functions in different source program files can also be called to each other. You can also specify that functions cannot be called by other files as needed. Functions can be divided into internal and external functions based on whether the function can be called by other source program files.

If a function can only be called by other functions in this file, it is calledInternal functions. When defining an internal function, add static before the function name and function type. Internal functions are also calledStatic Functions. By using internal functions, You can restrict the functions to only the files where they are located. If different files contain internal functions with the same name, they do not interfere with each other.

Usually, the functions and external variables that can only be used by the same file are put in one file, and all of them are preceded by static to make themLocalizationOther files cannot be referenced.

Because static variables or static functions are only valid in the current file (the file defining it), we can completely, defines two or more static variables or functions with the same name. In this way, when multiple independently compiled source files are linked to a program, the static modifier avoids the conflict between the external variables in a file and the variables in other files due to the same name.

For example, two static variables A are defined in file a and file B:

File A: static int;

File B: static int;

These two variables are completely independent and do not have any relationship between them. They occupy their respective memory addresses. Changing the value of A in file a does not affect the value of a in file B.

Static Summary:

(1) first, the static function is hidden. Secondly, because the static variable is stored in the static storage area, it has persistence and default value 0. Initialized global variables and local static variables are stored in the. data Segment; uninitialized global variables and local static variables are stored in the. bss segment.

(2) member functions of C ++ classes cannot be both virtual and static, because the basic principle of polymorphism implementation is that each instance of a class with virtual functions should contain a pointer, point to the virtual function table (vtbl ). Static modified static member functions, as class functions, are not related to any instances and cannot realize polymorphism.

Refer:

Program Design and C language Liang Li

Nan Yu, vernacular C ++

Visual C ++ Object-Oriented Programming Tutorial Wang yujian

C ++ Primer Stanley B. Lippman

Programmer self-cultivation

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.