当前位置:网站首页>The C programming language (2nd) -- Notes -- 1.7
The C programming language (2nd) -- Notes -- 1.7
2022-07-27 11:28:00 【YovaVan】
1.7 function (Functions)
C The function in is equivalent to Fortran The subroutine of (subroutine) Or functions , It's also equivalent to Pascal The process of (procedure) Or functions . Function provides a simple method for computing encapsulation , Later, when using functions, you don't need to consider how to implement them . Use the function designed correctly , Programmers don't have to think about how the function is implemented , Just know what functions it has .C Medium simple 、 convenient 、 Use functions efficiently . We often see short functions that are called only once after definition , This makes the code snippet more legible .
So far, , Functions used (printf、getchar、putchar) Are functions provided by the function library . Now I have compiled some functions . C Didn't like Fortran Provide similar to ** Exponentiation operator of , Now write a power function power(m, n) To illustrate the method of function definition .power(m, n) Used to calculate integers m Of n The next power ,n It's a positive integer. . Function call power(2, 3) As the result of the 32. This function is not a practical power function , Can only handle A positive integer of a smaller integer The next power , But this is enough to illustrate the problem .( A calculation is provided in the standard library x Of y Power function pow(x, y).)
Here are the functions power(m, n) The definition of and the main program that calls it , You can see the complete program structure .
#include <stdio.h>
int power(int m, int n);
/* test power function */
main()
{
int i;
for (i = 0; i<10; ++i)
printf("%d %d %d\n", i, power(2,i),power(-3,i));
return 0;
}
/* power: raise base to n-th power; n >= 0 */
int power(int base, int n)
{
int i, p;
p = 1;
for(i = 1; i <= n; ++i)
p = p * base;
return p;
}The general form of function definition :
return type Function name (0 Or multiple parameter declarations )
{
Declaration part
Statement sequence
}Function definition We can use In any order Appear in the One or more source files in , But the same function cannot be stored in multiple files . If the source program is scattered in multiple files , Then you need to do more work when compiling and loading , But this is the operating system , It's not the attribute of language . Tentative assumption main and power The two functions are placed in the same file , What I learned earlier is related to function C Language program Your knowledge is still valid .
main The function was called twice in the following statement power function :
printf("%d %d %d\n", i, power(2, i), power(-i, 3));
On every call ,main Functional direction power Function passes two arguments ; When the call execution is completed ,power Functional direction main Function returns a formatted integer and prints . In the expression ,power(2, i) Same as 2 and i The same is an integer ( Not all functions result in integer values , See the first 4 Chapter ).
power Function number 1 That's ok
int power(int base, int n)Statement Type of parameter 、 name as well as The type of the result returned by this function .power The arguments to the function use names only in power Function internal valid , Not visible to any other function : Other functions can use the same parameter name without conflict . Variable i And p Again :power Function i And main Function i irrelevant .
Usually put Function definition Appear in the list in parentheses Variable be called Formal parameters , But the Function call China and The value corresponding to the formal parameter be called The actual parameter .
power The result of the function passes return Statement returned to main function . keyword return Can be followed by any expression , form :
return expression ; Functions do not always have return values ; Without expression return Statement will return control to caller , But no useful value is returned . This is equivalent to drawing curly braces at the right end of the function , The function is “ At the end ”. The main function (the calling fuction) You can also ignore the value returned by the function .
Be careful ,main There is a clause at the end of the function return sentence .main It's also a function , It can also caller Returns a value , The caller is actually The execution environment of the program . In a general way ,‘ The return value is 0’ Indicates normal termination ,‘ The return value is not 0’ Indicates an abnormal condition or an error ending condition . For simplicity , Ahead main Functions are omitted return sentence , But in the future main Function contains return Sentence to remind everyone of : The program also returns status to its execution environment .
Appear in the main Declaration statement before function
int power(int m, int n) ;indicate power There are two functions int Parameters of type , And return a int Type value . This declaration is called a function prototype , It has to work with power The definition and usage of the function are consistent . If the definition of function 、 Usage is inconsistent with the prototype of the function , Will make a mistake .
The function prototype And Statement in Parameter name The same is not required . in fact , The parameter name in the function prototype is optional , The above function prototype can also be written as :
int power (int, int);but , Appropriate Parameter name can rise To very good Illustrative effect , Therefore, the parameter name is always indicated in the function prototype .
review ,ANSI C Same as earlier versions C The biggest difference between languages is Function declaration and definition . Press C The original definition of ,power The function should be written as :
/* power: raise base to n-th power;n>=0 */
/* (old-style version) */
power(base, n)
int base, n;
{
int i, p;
p = 1;
for (i = 1; i <= n; ++i)
p = p * base;
return p;
}among , Parameter name Specify , Parameter type Declare before the left curly bracket . If the type of a parameter is not declared , The default is int type . Function body and ANSI C In the same form .
stay C In the original definition of language , It can be declared at the beginning of the program in the following form power function :
int power();Parameter lists are not allowed in function declarations , So the compiler cannot check at this time power Legitimacy of function calls . in fact , power By default, the function will be assumed to return int Type value , Therefore, the declaration of the whole function can be ignored .
stay ANSI C In the function prototype syntax defined in , The compiler can easily detect errors in the number and type of parameters in function calls . ANSI C Old style function declarations and definitions are still supported , This can at least have a transitional stage . But it is strongly recommended that : When using the new compiler , It's best to use the new function prototype declaration .
practice 1-15 Rearrange 1.2 Temperature conversion procedure in section , Use function to realize temperature conversion calculation .
边栏推荐
- Longest ascending subsequence model acwing 272. longest common ascending subsequence
- 6 find the smallest letter larger than the target letter
- 10 complete half of the questions
- Where is the big data open source project, one-stop fully automated full life cycle operation and maintenance steward Chengying (background)?
- Instructions for mock platform
- Game theory acwing 891. Nim game
- 2022 Niuke multi school (3) j.journey
- 树形DP AcWing 285. 没有上司的舞会
- Caused by:org.gradle.api.internal.plugins . PluginApplicationException: Failed to apply plugin
- 最长上升子序列模型 AcWing 272. 最长公共上升子序列
猜你喜欢

树形DP AcWing 285. 没有上司的舞会

Tree DP acwing 285. dance without boss

最长上升子序列模型 AcWing 1017. 怪盗基德的滑翔翼

Redis simple to use

Knapsack model acwing 1024. Packing problem

Game theory acwing 892. Step Nim game

高斯消元 AcWing 884. 高斯消元解异或线性方程组

博弈论 AcWing 891. Nim游戏

Digital triangle model acwing 1027. Grid retrieval

State compression DP acwing 91. shortest Hamilton path
随机推荐
Quantitative industry knowledge summary
State compression DP acwing 91. shortest Hamilton path
Win10 vscode code code format setting and remote breakpoint debugging
What is the mystery of the gate of the meta universe?
ACM warm-up Exercise 1 in 2022 summer vacation (summary)
Verilog implementation of ECG signal acquisition, storage and transmission system based on FPGA
IO stream_ Character stream, IO stream summary, IO stream case summary
最长上升子序列模型 AcWing 1017. 怪盗基德的滑翔翼
Game theory acwing 891. Nim game
Raw socket grabs packets, and packets on some ports cannot be caught
"My" bug collection (Reprinted)
(9) Shell I / O redirection
What is the issuing price of NFT (Interpretation of NFT and establishment of NFT world outlook)
Luogu p1441 weight weighing
Internal and external troubles of digital collection NFT "boring ape" bayc
【着色器实现Shake随机摇动效果_Shader效果第十篇】
求组合数 AcWing 888. 求组合数 IV
14 check whether integers and their multiples exist
Remember an experience of using canvas to make the banner streamer effect of Tencent cloud homepage
Where is the big data open source project, one-stop fully automated full life cycle operation and maintenance steward Chengying (background)?