IOS Development Series--detailed explanation of C language storage mode and scope _ios

Source: Internet
Author: User
Tags function definition printf reserved variable scope

Overview

Basically every language has to discuss this topic, C is no exception, because only you fully understand each variable or function storage mode, scope and destruction time to correctly use the language. Today, we will focus on the scope, storage mode, lifecycle, scope and accessibility of variables in C language.

    • Variable scope of action
    • Storage mode
    • Accessibility

Variable scope of action

In C, variables range from scope to global variables and local variables. Global variables can be used in all functions after the definition, as long as the previous code has been modified, then the subsequent code to use is the modified value, the scope of the local variable is generally within a function (usually within a pair of curly braces {}), outside the program can not access it, it has access to the outside variables.


//MAIN.C
//scopeandlifecycle////
Created by Kenshin Cui on 14-7-12.
Copyright (c) 2014 Kenshin Cui. All rights reserved.

#include <stdio.h>

int a=1;
void ChangeValue () {
 a=2;
 printf ("a=%d\n", a);
}
int main (int argc, const char * argv[]) {
 int b=1;
 ChangeValue (); Results: a=2
 printf ("a=%d,b=%d\n", a,b);//results: A=2,b=1, because ChangeValue modified this global variable return
 0;


How variables are stored

The strength of the C language is that it can manipulate memory directly, but to be fully familiar with its way of doing it we have to figure out how it is stored. The location of the storage variables is divided into normal memory (static storage), runtime stack (dynamic store), hardware register (dynamic Store), and of course the efficiency of these kinds of storage is from low to high. And according to the different storage location in C language can be divided into variables: Static variables, automatic variables, register variables.

static variables

Let's start with the static variables stored in normal memory, global variables and local variables that use static declarations are static variables that are initialized only once during the system run (in the example below, although variable B is a local variable that cannot be accessed externally, his life cycle continues until the end of the program). The variable c is released the first time it is executed and re-created the second time it is executed.


//2.1.c
//scopeandlifecycle////
Created by Kenshin Cui on 14-7-12.
Copyright (c) 2014 Kenshin Cui. All rights reserved.

#include <stdio.h>

int a=1;//Global variables are stored in static memory, only a

void ShowMessage () {
 static int b=1 is initialized once; Static variables are stored in static memory, and the second call does not initialize
 int c=1;
 ++b;
 a+=2;
 printf ("a=%d,b=%d,c=%d\n", a,b,c);
}

int main (int argc, const char * argv[]) {
 showmessage ();//Result: A=3,b=2,c=1
 showmessage ();//Results: A=5,b=3,c=1 return
 0;
}

Automatic variable

The local variable modified by the keyword Auto is an automatic variable, but the Auto keyword can be omitted, so it can be concluded that all local variables not modified by static are automatic.

 

Of course, the stacks and heaps of stored automatic variables are actually two completely different spaces (although all are in the runtime valid space): the stack is usually automatic program allocation, its storage results similar to the data structure of the stack, advanced, after the end of the program by the compiler automatically released, and the heap is the developer manual encoding allocation, If you do not manually release it, you wait until the program finishes running the operating system recycle, and its storage structure is similar to a linked list. In the above code, the P variable is also an automatic variable, which can also be decorated with auto, except that the content it points to is placed on the heap (p itself is stored on the stack).

Here are some points: the space allocated by malloc is logically continuous, it may not be physically continuous; P must be manually released, otherwise the memory occupied by the program will remain occupied until it is run; the process of releasing p only releases the space that P points to, and the address stored in P is not released and needs to be manually set to NULL. Otherwise it would be a useless wild pointer;

Register variable

By default, both automatic and static variables are in memory, and the difference is that the automatic variable is placed in a special memory allocated by the runtime. But the register variable is in the hardware register, physically speaking it and memory in two completely different hardware. Everyone knows that the register storage space is very small, but its efficiency is very high, so the reasonable use of register variable is very important. What is a register variable? A non-static local variable that uses the register-decorated int or char type is a register variable. Yes, you need three conditional support: Register modifier, must be int or char type, must be non-static local variable.

In addition to storage locations, register variables fully conform to the conditions of an automatic variable, so its lifecycle is exactly the same as an automatic variable, and it is automatically released when the function is finished. Because the register space is precious, so we need to use the register variable reasonably, we only consider using the register variable, if too many of the register variables are defined, automatically convert to the automatic variable when the register space is not enough.


//1.3.c
//scopeandlifecycle////
Created by Kenshin Cui on 14-7-12.
Copyright (c) 2014 Kenshin Cui. All rights reserved.

#include <stdio.h>

int main (int argc, const char * argv[]) {
 Register int a=1;
 printf ("a=%d\n", a);
 return 0;
}

The above we talk about the storage type of variables, in fact, there are two storage types in C language: Constant storage and code store, respectively, for storing string constants, using the const modified global variables and binary function code.

Accessibility

There are no other modifiers in the C language, public, private, to qualify the valid range of variables and functions, but there are two similar keywords that can achieve similar effects: extern and static.

extern

extern Acting on variables

We know that in the C language the order of the variables is strict, and the use of variables must be defined before use, and extern is used to declare a variable that already exists, so that even if you define a variable later, you can use it as long as it is declared earlier. Specific details through the following code to believe that everyone can see:

2.1.C//Scopeandlifecycle////Created by Kenshin Cui on 14-7-12. Copyright (c) 2014 Kenshin Cui.
All rights reserved. #include <stdio.h>//If a variable A is defined under the main function, it is not possible to use a in main if no declaration is made on main;//Similarly, if an extern declaration is not defined, the error will be incorrect. Because extern is not responsible for defining variable A but simply declaring a variable that has already been defined;//Of course, if you define int a on main, it's OK to remove the definition below main, which is equivalent to the definition above, But if all two places define a, the program considers the above definition to be a declaration, except that the extern keyword is omitted;//The first case is defined below without declaration, error int main (int argc, const char *
 Argv[]) {printf ("a=%d\n", a);
return 0;

int A;
The second case, defined above, is correct int A;
 int main (int argc, const char * argv[]) {printf ("a=%d\n", a);
return 0;
The//third case, defined below, is stated above, the correct extern int A;
 int main (int argc, const char * argv[]) {printf ("a=%d\n", a);
return 0;


int A;
In the fourth case, only the above declaration (compile-time no problem, because the above statement cheated the compiler, but the runtime is wrong, because extern can only declare a defined variable), error extern int A;
 int main (int argc, const char * argv[]) {printf ("a=%d\n", a);
return 0;
The//fifth case, both up and down are defined (this way is correct, because the above definition is considered to omit the extern declaration), the correct int A; int main (int argc, const char * argv[]) {printF ("a=%d\n", a);
return 0;
int A;
In fact, the following situation is also not error int A;
int A;
 int main (int argc, const char * argv[]) {printf ("a=%d\n", a);
return 0;
int A;

int A;
In the sixth case, the global variable is declared as a local variable, but its essence or global variable, the correct int A;
 int main (int argc, const char * argv[]) {extern int A;
 printf ("a=%d\n", a);
return 0;

int A;
In the seventh case, redefine a variable a within the function, although no error, but two A is not the same int A;
 int main (int argc, const char * argv[]) {int A;
printf ("a=%d\n", a);//Note that the output of a is actually an internally defined a, which has no relation to a defined outside function return 0;

 int A;

If two files define a global variable at the same time, then essentially they are referring to the same variable. As can be seen from the example below, the variable a value in Message.c is modified after the variable A has been modified in MAIN.C.

Notice that in the above code, regardless of whether a definition is preceded by an extern in Message.h, or before a in main.h, and extern results are the same, extern applies. As in a single file, you cannot add extern to two definitions, otherwise there is no definition. If you remove the definition (or declaration) of a in message.c, then it can access the global variable A in main.c, and the answer is no (this is the same as defining a function in one file that is directly used in another file without declaring it).

extern acts on functions

An extern function is no longer a simple declarative function, but rather a function as an external function (and, of course, an internal function, as the following says), which is also accessible in other files. But you should have noticed that in the above code in the message.c in front of the showmessage did not add an extern keyword, in the MAIN.C is not the same access? That's because this keyword can be omitted, and by default all functions are external functions.

and acting on the variable, the above main.c and message.c in the extern can be omitted, where the role of extern is to define or declare an external function. From the above you can see in different files can define the same variable, they are considered the same variable, but it should be pointed out that the external function in a program is not the same name, otherwise it will report an error.

Static

Static acts on variables

In fact, we've seen the use of the static keyword in a variable in the previous example, using static to set a local variable, and we emphasize that the static local variable is initialized only once in the function. So what if static works on global variables? If static acts on a global variable, its role is to define a global variable that can only be accessed in the current file, equal to the private global variable.

From the output above, we can see that the variable a in message.c and MAIN.C is not the same variable, in fact the variable a in message.c can only be used in message.c, although the variable A in MAIN.C is a global variable but the nearest principle, MESSAGE.C will use its own internal The variable A. Of course, the variable a defined in MAIN.C in the example above is the same as the result of a static global variable, except that if there are other source files, the A variable cannot be used. However, a in MAIN.C cannot be declared extern because MAIN.C cannot access variable A in message.c so that there is no definition of variable a in main.c.

Static acts on functions

A static action on a function is similar to a variable, and if static acts on a function, the function is an intrinsic function, and the code in the other file is not accessible. The following code will complain at run time because the ShowMessage () function in mesage.c is private and can be passed in the compile phase, although declared in Main.c, but the error occurs during the link phase.

Summarize

Finally do a simple summary:

    1. extern acts on a variable to declare a variable that has already been defined, but it does not define a variable; using extern you can use global variables in other files (of course, at this point extern can omit);
    2. extern acts on a function a bit like it does with global variables, declaring this function is an external function, other files can be accessed, but the difference is that when it acts on a function, it can not only declare a function but also define a function (used in front of the function definition), whether the definition or declaration can be omitted, The C language defaults to the function definition or declaration as an external function;
    3. When static is applied to a variable, it is defined only once and is not redefined later when it is used, and when static is applied to a global variable, it indicates that the variable is accessible only in the current file and not in other files;
    4. Static acts on a function like a global variable, declaring or defining that the function is an internal function (also called a static function) that cannot be accessed in other files outside the file where the function resides;

Original link: http://www.cnblogs.com/kenshincui/p/3854243.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.