当前位置:网站首页>Scope and category of C language variables - learning 20
Scope and category of C language variables - learning 20
2022-06-12 00:38:00 【XG. Solitary dream】
This paper is finally updated at 2022 year 02 month 14 Japan , Has more than 13 I didn't update it . If the article content or picture resources fail , Please leave a message for feedback , I will deal with it in time , thank you !
Scope of variable
- In the program, you can The range in which variables are accessed be called Scope of variable .
- Depending on the scope of the variable , Variables are divided into local variable and Global variables .
- local variable
- In a Function body or compound statement Defining variables is called local variable .
- local variable Only valid within the function body or compound statement that defines it , namely It can only be inside the function body or compound statement that defines it Use it , And in the Outside the function body or compound statement that defines it You can't use it .
- Example
#include <stdio.h>
void main(){
int i,a,b; // Defining local variables i,a,b
i = i + 1; // have access to i
{
int c;
c = a + b; // c It works in this range ; a, b It works in this range
}
c = c + 1; // c Invalid in this range
}
int add(int x,int y){
int j; // Defining local variables j
j = x + y; // have access to j
i = x + y; // Out of commission main Local variables in functions i, The system will prompt i Not a statement
}Global variables
- stay Variables defined outside the function definition be called Global variables .
- Global variables can be in The file that defines it uses , Its scope is From its definition to the end of the file where the variable is located .
- Example
#include <stdio.h>
int i,j,a,b, n = 5; // Define global variables
void main(){
a = 5;
b = 6;
i = a + b;
{
j = a - b; // c It works in this range ;a,b It works in this range
}
int add(int x); // Function declaration
printf("i = %d, j = %d, m = %d\n",i,j,add(5));
}
int add(int x){
int m;
m = n + 1; // have access to n
return m;
}Suggest :
- Do not use global variables when not necessary , Here's why :
- 1. Global variables are used throughout the execution of the program all Occupied storage unit , It's only when you need to open up units .
- 2. Too many global variables , Will reduce the clarity of the program . It is possible to change the value of external variables when each function is executed , The program is error prone , So limit the use of global variables .
- 3. Reduce the versatility of functions . Because a function depends on its external variables when it is executed . If you will - Move a function to another file , Also move the relevant external variables and their values together . But if the external variable has the same name as the variable in other files , There will be problems , It reduces the reliability and generality of the program .
- It is generally required to put C In program Function as a closed body , Only through “ Actual parameters - Shape parameter ” the_channel_of_communication_with_the_outside_world_ .
If the external variable has the same name as the local variable , That is, when the global variable and the local variable have the same name , Local variables take precedence !
#include <stdio.h>
int a = 3, b = 5; // a,b For external variables
void main()
{
int a = 8; // a Is a local variable
printf("%d\n", max(a, b));// here a Is a local variable ,b Is a global variable
}
max(int a,nt b)
{
int c;
c = a > b ? a : b; // Shape parameter a、b The scope of action is only max In the function
return (c);
}Storage category of variables
- 1. Dynamic storage and static storage
- From variable Scope ( From space ) angle Come to share , Can be divided into Global variables and local variable .
- From variable values The time angle of existence Come to share , Can be divided into Static storage and Dynamic storage .
- Static storage :
- Means that the program is run by The system allocates fixed storage space The way .
- Dynamic storage :
- While the program is running Dynamically allocate storage space as needed The way .
- This storage space can be divided into three parts :
- Procedure area
- Static storage area : Global variables
- Dynamic storage : The formal parameter of the function 、 Variables defined in functions 、 Function call field protection and return address, etc
- Variables and functions have two properties : data type and Storage category of data .
- Storage category refers to The way data is stored in memory .
- There are two types of storage : Static storage class and Dynamic storage class . contain :
- automatic ( auto ) ;
- Static ( static ) ;
- The register of ( register ) ;
- External ( extern ).
- According to the... Of the variable Storage class , You can know the... Of variables Scope and lifetime .
auto Variable
- automatic auto, Not specifically declared as static Storage category Local variables are dynamically allocated storage space , stay When the function is called The system will give they Allocate storage space , stay At the end of a function call Just Automatically free up these storage spaces . Therefore, this kind of local variable is called automatic variable .
- Parameters in functions and variables defined in functions ( Include variables defined in compound statements ), Both belong to this category. .
- use keyword auto As a storage category Statement .
- Example
int f(int a) // Definition f function ,a Is a formal parameter
{
auto int b,C=3; // Definition b、C For automatic variables
}- keyword auto It can be omitted .
auto int a,b,c=3;Andint a,b,c=3;The two are equivalent
static Static local variables
- Static static, When the value of a local variable in a function is After the function call ends, it does not disappear but keeps the original value , This variable is called Static local variables .
- With keywords static Make a statement .
- Example
#include <stdio.h>
void main()
{
int f(int a);
int a = 0, i;
for (i = 0; i < 3; i++) {
printf("%d\n", f(a));
}
}
int f(int a) { // Every call , Open up new a and b, however c No,
auto b = 0;
static c = 0;
b++;
c++;
return (a + b + c);
}
- Static local variables belong to the category of static storage , Allocating storage units within a static storage area . In procedure It doesn't release during the whole operation .
- Dynamic local variables belong to the category of dynamic storage , Occupy dynamic storage space and Does not occupy static storage space , Release at the end of a function call .
- Static local variables yes Assign initial value at compile time Of , That is, the initial value is assigned only once , When the program is running, it has an initial value . in the future Each time a function is called, the initial value will not be reassigned, but the value at the end of the last function call will be retained .
- If in Local variables are defined without initial values , On the other hand Static local variables Come on , Compile time Automatically assign initial value 0 ( Yes Numerical type Variable ) or Null character ( Yes Character change The amount ). And yes Automatic variable Come on , If no initial value is assigned, then Its value is an uncertain value .
- although Static local variables In function call It still exists after the end , but Other functions cannot reference it .
Example
seek 1-5 The order of
#include <stdio.h>
void main()
{
int fac(int a);
int i;
for (i = 1; i <= 5; i++) {
printf("%d The factorial =%d\n",i, fac(i));
}
}
int fac(int a) {
static int f = 1;
f = f * a;
return (f);
}register Variable
- The register of register, The value of the variable is Store in memory Of , When the value of which variable is used in the program , The controller issues an instruction to change the value of the variable in memory To the arithmetic unit . Through the arithmetic unit , If you need to save , Then the data is sent to the memory from the arithmetic unit .
- If some variables are used frequently , It takes a lot of time to access the value of a variable .
- In order to improve the efficiency of execution ,C Language allows the value of a local variable to be Put it in CPU Register in in , It needs to be taken directly from the register to participate in the operation , You don't have to access it in memory .
- Because the access speed of register is much higher than that of memory , So doing so can improve execution efficiency . This variable is called Register variables .
- With keywords register Make a statement .
- Example
#include <stdio.h>
void main()
{
long fac(long);
long i, n;
printf(" Please enter an integer :");
scanf_s("%ld", &n);
for (i = 1; i <= n; i++){
printf("%ld The factorial =%ld\n", i, fac(i));
}
}
long fac(long n){
register long i, f = 1; // Define register variables
for (i = 1; i <= n; i++) {
f = f * i;
}
return(f);
}extern External variables
- External extern, A variable is in Global variables defined outside the function , Its scope is Start with the definition of the variable , To the end of this procedure .
- In this scope , Global variables can be referenced by various functions in the program . At compile time External variables are allocated in static storage .
- use extern To declare external variables , To extend the scope of external variables .
- Example
Declare external variables in a file
#include <stdio.h>
void main()
{
int max(int, int);
extern A, B; // Declare external variables
printf("%d\n", max(A, B));
}
int A = 15, B = 8; // Define external variables
int max(int x, int y){
int z;
z = x > y ? x : y;
return(z);
}Declare external variables in a multi file program , use extern Extend the scope of external variables to other files .
- Document I
#include<stdio.h>
int A; // Define external variables
void main(){
printf("%d\n",A++);
}- Document II
extern A = 100; // Statement A For a defined external variable
static Declare external variables
- In programming , some External variables are limited to references in this document It can't be referenced by other files . At this time, you can Add an... When defining an external variable static Statement .
- Example
- Document I
#include<stdio.h>
static int A; // Define external variables
void main() {
printf("%d\n", A++);
}- Document II
extern int A; // Can't use Global variables
void fun(int n) {
A = A * n;
}About the declaration and definition of variables
- Definitional statement : Need to build storage space ( Such as :
int a;) Statement . - Referential statement : No need to create a storage space declaration (
extern a;). - Be careful :
- The statement includes definitions , But not all statements are definitions .
- Yes
int a;for , It has both a statement , Another definition . - And yes
extern a;for , It's a statement, not a definition .
summary
- 1. from Scope angle branch , Yes Local and global variables . They use the following storage categories :
- Local variables include :
- Automatic variable 、 Static local variables 、 Register variables .
- Global variables include :
- Static external variables 、 External variables .
- Formal parameters can be defined as Automatic variable or Register variables .
- Local variables include :
- 2. Dependent variable Time of existence To distinguish between , Yes Dynamic storage and Static storage Two types of .
- Dynamic storage :
- Automatic variable 、 Register variables 、 Formal parameters .
- Static storage :
- Static local variables 、 Static external variables 、 External variables .
- Static storage means that the whole running time of a program exists , Dynamic storage is the temporary allocation of units when calling functions .
- Dynamic storage :
- 3. Distinguish from the location where the variable value is stored , Can be divided into :
- Static storage area in memory :
- Static local variables 、 Static external variables 、 External variables .
- Dynamic memory area in memory :
- Automatic variables and formal parameters .
- CPU Register in :
- Register variables .
- Static storage area in memory :
- 4. About the concept of scope and lifetime
- Scope : If a variable is in Within the scope of a file or function It works , This range is called this Scope of variable .
- Life span : If a variable value is in There is a moment Of , Think that this moment belongs to Lifetime of variables .
- Scope is from the perspective of space , Life span is from the perspective of time .
Internal and external functions
- Depending on whether the function can be called by other source files , Distinguish functions into Internal function and External function .
Internal function
- Internal functions are also called static functions , It can only be called by other functions in the file that defines it , It cannot be called by functions in other files , That is, the scope of the internal function is only limited to this document .
- When defining internal functions , stay The function name and function type are prefixed with static. namely
staticType identifierFunction name ( Formal parameter table ) - for example :
static int fun( inta, intb)
External function
- When defining a function , If you add a keyword at the leftmost end of the function's head extern, It means that this function is External function , It can be called by other files .
- for example :
- The first part of the function can be written as
extern int fun (int a,int b)such , function fun You can call... For other files .
- The first part of the function can be written as
- If you define a function Omit extern , Is implied as External function .
- In the file where you need to call this function , use extern Declare a function , Indicates that the function is an external function defined in another file .
- Example
There's a string , There are several characters in the , Enter a character , The program is required to delete this character from the string . Implemented with external functions .
- Document I main The main function
#include<stdio.h>
void main() {
extern void estring(char str[]);
extern void dstring(char str[], char ch);
extern void pstring(char str[]);
char c, str[80];
printf(" Please enter a string of characters :\n");
estring(str);
printf(" Please enter a character to delete :\n");
scanf_s("%c", &c);
dstring(str, c);
pstring(str);
}- Document II dstring Delete character function
void dstring(char str[], char ch) {
int i, j;
for (i = j = 0; str[i] != '\0'; i++) {
if (str[i] != ch) {
str[j] = str[i];
j++;
}
}
str[j] = '\0';
}- Document 3 estring Receive input function
#include <stdio.h>
extern void estring(char str[80]) {
gets(str);
}- Document IV pstring Printout function
#include <stdio.h>
void pstring(char str[]) {
printf("%s\n", str);
}边栏推荐
- Alibaba cloud intelligent coding plug-in provides a more cosy development experience
- Jmeter性能测试场景的创建和运行
- 926. Flip String to Monotone Increasing
- 详解异步任务:函数计算的任务触发去重
- 苹果手机wps如何改字体大小
- 1、 Getting started with flutter learn to write a simple client
- IP编址概述
- Wechat applet Chinese English conversion
- repeat_ L2-007 family property_ set
- How to strengthen the prevention and control of major safety risks for chemical and dangerous goods enterprises in flood season
猜你喜欢
![[pat (basic level) practice] - [simple simulation] 1076 WiFi password](/img/e4/82bdc74dcaa9f397c81135da0c0097.jpg)
[pat (basic level) practice] - [simple simulation] 1076 WiFi password

Cuiyunkai, CEO of Gewu titanium Intelligent Technology: data value jump, insight into the next generation of change forces

Wechat applet Chinese English conversion

The time selector style is disordered and the middle text is blocked

How to package and send compressed files for mobile WPS

月份选择器禁用当月以后的数据 包含当月

Why are the values of ordereddict not equal- Why are the values of an OrderedDict not equal?

Month selector disable data after the current month to include the current month

2022 Tibet latest special worker (construction elevator) simulation test question bank and answers

Explore table component virtualization
随机推荐
Global and Chinese maleic anhydride polypropylene industry investment analysis and prospect trend forecast report 2022 Edition
730.Count Different Palindromic Subsequences
DevOps落地实践点滴和踩坑记录-(1)
win10系统pscs6如何卸载
Hertzbeat v1.0 beta. 4 release, easy-to-use and friendly monitoring alarm system
Characteristics of JS logical operators
Month selector disable data after the current month to include the current month
DDD exaggeration, Eric Evans made a bad start
Is the o2o platform worth doing in 2022
模块八-设计消息队列存储消息数据的 MySQL 表格
Wechat applet Chinese English conversion
[industry application] an article on power digital transformation
Flutter uses local pictures
手机wps如何压缩文件打包发送
2022 Tibet latest special worker (construction elevator) simulation test question bank and answers
MySQL basic tutorial -- MySQL transaction and storage engine
[answer] in the business sequence diagram of XX shopping mall, is it drawn as a business executor (bank) or a business entity (banking system)
2022 edition of global and Chinese sodium hydrosulfide market in-depth investigation and prospect Trend Forecast Report
[day 7 of JUC learning] reentrantlock and reentrantreadwritelock
Alibaba cloud intelligent coding plug-in provides a more cosy development experience