当前位置:网站首页>The C programming language (2nd) -- Notes -- 1.10
The C programming language (2nd) -- Notes -- 1.10
2022-07-27 11:31:00 【YovaVan】
1.10 External variables and scopes
main Variables in functions ( Such as line,longest) yes main Private function private Or local local Variable . They are declared on main Inside , So no other function can directly access them . The same is true of function variables declared by other functions . example ,getline The variable declared by the function i And copy Functional i irrelevant . Each local variable in a function only when the function is called There is , When the function exits after execution disappear . This is also the reason why other languages often call such variables automatic variables . Later “ Automatic variable ”(automatic henceforth) representative “ local variable ”.( Chapter four will discuss stastic Storage class , This kind of local variable keeps its value unchanged between multiple function calls .)
Because automatic variables are only used in function calls 、 During execution , therefore , Between calls to a function , Automatic variables do not retain the assignment from the previous call , And it should be explicit every time you enter the function 【adv. Clearly , In detail ; Directly , Frankly ; Blatantly , Not implicitly 】 For the assignment . If the automatic variable is not assigned , Then the invalid value is stored in it .
Except for automatic variables , You can also define variables outside all functions , namely , Variable names can be used in all functions 【 Come on 】 Access this type of variable ( This mechanism is the same as Fortran in COMMON or Pascal Variables declared by the outermost block of a language ). Because external variables can be accessed globally , therefore , Functions can exchange data through external variables , Instead of using a parameter table . also , External variables exist during program execution , Instead of generating... When a function is called , Disappear when the function finishes executing . Even after the function assigned to the external variable returns , These variables will remain unchanged .
External variables must be defined outside of all functions , And it can only be defined once , After definition, the compiler will allocate storage units for it . In each function that needs to access external variables , The corresponding external variable must be declared , In this case, the type . When declaring, you can use extern Statement explicitly declares , It can also be implicitly declared by context . To discuss external variables in more detail , Rewrite the above program for printing the longest text line , hold line、longest And max Declared as an external variable . This requires modifying the calls of these three functions 、 Declaration and function body .
int getline(void);
void copy(void)
/*print longest input line; Specialized version.*/
main()
{
int len;
extern int max;
extern char longest[];
max = 0;
while ((len = getline()) > 0)
if (len > max) {max = len ;
copy ();
}
if (max > 0) /* There was a line.*/
printf("%s", longest );
return 0;
}
/* getline: Specialized version*/
int getline(void)
{
int c, i;
extern char line[];
for (i = 0; i < MAXLINE - 1
&& (c = getchar)) != EOF && c != '\n'; ++i)
line [i] = c;
if (c == '\n'){
line[i] = c;
++i;
}
line [i] ='\0';
return i;
}
/* copy Specialized version */
void copy (void)
{
int i;
extern char line[], longest[];
i = 0;
while ((longest [i] = line[i]) != '\0')
++i;
}The first few lines of this example define main、 getline And copy Several external variables used by the function , Declare the type of each external variable , In this way, the compiler will allocate storage units for them . From the perspective of grammar , The definitions of external and local variables are the same , But because they are outside the functions , So these variables are external variables . Function before using external variables , You must know the name of the external variable . One way to achieve this is to use extern Declaration of type . This type of declaration , In addition to adding a keyword in front extern Outside , Other aspects are the same as the declaration of ordinary variables .
In some cases, it can be omitted extern Statement . In the source file , If the definition of an external variable appears before the function that uses it , Then there is no need to use extern Statement . therefore ,main、getline And copy Some of them extern Statements are superfluous . In common practice , The definitions of all external variables are placed at the beginning of the source file , So you can omit extern Statement .
If the program is contained in multiple source files , And a variable in file1 The document defines 、 stay file2 and file3 Use... In the document , So in the file file2 and file3 You need to use extern Declaration to establish the relationship between the variable and its definition . Usually, variables and functions extern The declaration is in a separate file ( It is customarily called header file ), And use... At the beginning of each source file #include Statement to include the header file to be used . Suffix named .h The Convention is the extension of the header file name . For example, functions in the standard library are similar to <stdio.h> Declared in the header file of . For more details, see 4 Chapter , The first 7 Chapter 、 appendix B We will discuss function libraries .
In the above special edition , because getline And copy Functions take no arguments , So logically , At the beginning of the source file , Their prototype should be getline() And copy(). But in order to match the old version C Language program compatibility ,ANSI C The language treats empty parameter tables as old versions C Language declaration , And do not check the parameter table any more . stay ANSI C in , If you want to declare an empty parameter table , Keywords must be used void Make an explicit statement . See Chapter 4 .
Be careful , In this section, definitions are used cautiously when discussing external variables (define) And statement ( declaration) These two words . “ Definition ” Means to create variables or allocate storage units , and “ Statement ” It means describing the nature of the variable , But no storage units are allocated .
Shun Ti , Now more and more people use everything they use as external variables , Because it seems that this can simplify the communication of data —— The parameter table is shorter , And you can always access these variables when you need them . however , Even when external variables are not used , They also exist . Over reliance on external variables can lead to certain risks , Because it will make the data relationship in the program ambiguous —— The value of an external variable may be accidentally or inadvertently modified , And the modification of the program becomes very difficult . Previously written “ Print the longest line of text ” Of the program 2 The first version is not as good as the 1 A good version , There are two reasons , One is the use of external variables ; On the other hand , The first 2 The functions in the three versions write the names of the variables they manipulate directly into the functions , Thus, these two useful functions lose their generality .
up to now , Have been to C The traditional core of the language is introduced . With the help of these few language elements , It has been able to write useful programs on a considerable scale . Readers are advised to spend some time writing programs as exercises . The following exercises are more complex than the program written earlier in this chapter .
practice 1-20 Programming detab, Replace the tabs in the input with the appropriate number of spaces , Fill the space to the next tab stop . Suppose the position of the tab stop bit is fixed , Like every other n Column will have a tab stop . n Should it be a variable or a symbolic constant ?
practice 1-21 Programming entab, Replace the space string with the minimum number of tabs and spaces . But keep the space between words the same . Suppose the position of tab stop and practice 1-20 Of detab The procedure is the same . When a tab or a space can be used to reach the next tab , Which replacement character is better ?
practice 1-22 Write a program , Put the longer input line “ fold ” In two or more shorter lines , The position of the break line is on the input line n After the last non space before the column . To ensure that the program can intelligently handle the situation when the input line is very long and there is no space or tab before the specified column .
practice 1-23 Write a delete C All comment statements in language programs . To handle quoted strings and character constants correctly . stay C In language , Comments cannot be nested .
practice 1-24 Write a program , lookup C Basic grammatical errors in language programs , Such as parentheses 、 square brackets 、 Curly braces do not deserve equivalence . Handle quotation marks correctly ( Include single and double quotes )、 Escape character sequences and comments .( If the reader wants to write a completely general program of this program , It will be more difficult .)
边栏推荐
- 数字三角形模型 AcWing 275. 传纸条
- 背包模型 AcWing 1024. 装箱问题
- 最长上升子序列模型 AcWing 482. 合唱队形
- Vscode establishes automatic search of header files under non engineering directories
- Find the combination number acwing 888. find the combination number IV
- tensorflow运行报错解决方法
- Sorry, you guys have something to deal with in the bank recently, which has been delayed
- Internal and external troubles of digital collection NFT "boring ape" bayc
- 9 UAV array
- Gaussian elimination acwing 884. Gaussian elimination for solving XOR linear equations
猜你喜欢

A deep analysis of the soul of C language -- pointer

The longest ascending subsequence model acwing 1017. The glider wing of the strange thief Kidd

Find the combination number acwing 886. find the combination number II

49 letter ectopic grouping and 242 effective letter ectopic words

Chinese remainder theorem acwing 204. strange way of expressing integers

高斯消元 AcWing 883. 高斯消元解线性方程组

Wechat push - template message parameter configuration

Stack acwing 3302. Expression evaluation

最长上升子序列模型 AcWing 482. 合唱队形

Installation and use of GTEST and gmock
随机推荐
Longest ascending subsequence model acwing 482. Chorus formation
7 row K with the weakest combat effectiveness in the matrix
Smart pointer (shared_ptr, unique_ptr, weak_ptr)
Find the combination number acwing 887. find the combination number III
第13章 IO流
博弈论 AcWing 891. Nim游戏
Stm32f10x -- C Language-1
Gaussian elimination acwing 884. Gaussian elimination for solving XOR linear equations
区间问题 AcWing 906. 区间分组
properties文件
C programming language (2nd Edition) -- Reading Notes -- 1.4
XXX packages are looking for funding run 'NPM fund' for details solutions
数字三角形模型 AcWing 275. 传纸条
9 UAV array
深析C语言的灵魂 -- 指针
Raw socket grabs packets, and packets on some ports cannot be caught
Miscellaneous records of Finance
C programming language (2nd Edition) -- Reading Notes -- 1.5
Find the combination number acwing 888. find the combination number IV
Knapsack model acwing 423. Picking herbs