当前位置:网站首页>An analysis of C language functions
An analysis of C language functions
2022-06-27 23:43:00 【Embedded universe】
List of articles
Preface
The function is C An important part of language , You can say that , Just use C Language to write a project , Then you must be able to use the function , Because of the function , It enables us to modularize when writing code , A function corresponds to a function , Avoid making wheels repeatedly . In this paper, we will do some research for you in the way of theory before practice C Explanation of language functions .
One 、 Definition of function
1. What is a function ?
C A function in a language is actually a code module to complete a specific function , In other words, a function is a small function . When we need to implement this small function in a certain scenario, we just need to call this function , Without the function , We may need to implement the whole process every time we implement a function , But the operation is the same every time , So our code will have a lot in common , This not only makes the code less readable , And it's big , And they are all repeated , This is certainly unacceptable . The introduction of function solves this problem . For a large project , We can split it into several small projects , Each small project has several small functions , It is encapsulated and implemented by several functions , Finally realize the whole project .
2. How to define a function ?
2.1 Definition of function ( Important theory )
< data type > < The name of the function >( < Formal parameters 1, Formal parameters 2, ......> )
{
Statement sequence ;
return [(< expression >)];
}
- data type :
(1) The data type is the return value type of the entire function . return The following expression types need to be consistent with the data types here .
(2) If you don't want to return a value for a function , Then the return value type should be written as void.
(3) If the return value type is written as void, Then the function does not need to write return, Or you could write it as return ;, That is to say return The following expression needs to be omitted .
(4) If the data type of a function is omitted , So the data type of the function is int type ., In other words , When the return value type of the function is int when , The effect is the same as that of not writing the return value . But from the perspective of programming specification , Omitting the data type of a function is not recommended . - The name of the function :
Must follow C The naming rules for language identifiers are sufficient . - Formal parameters :
Here are the formal parameters of the function , It's called formal parameter for short , The formal parameter is added by the variable data type Variable names consist of , If there are multiple formal parameters , Each formal parameter is separated by commas . The formal parameter is inside the bracket , If there are no formal parameters, you can omit them , You can write only one void, But parentheses cannot be omitted .
The scope of a formal parameter can only be accessed in braces of a function . Function cannot be accessed outside . Through this sentence, it indirectly shows , We can define the same variables on the outside of the function and on the formal parameters of the function , And the data types of the two variables are the same , The variable scope outside the function is outside the function , The formal parameter scope of the function is in the function , Their two most common variables have the same name , But the scope is different , That is, the address spaces of the two variables are different , Operate on any of these variables , Another variable with the same name will not be affected . This is especially noteworthy for beginners . - A pair of braces :
Inside the braces is the implementation process of the function , Consists of a sequence of statements . Call a function , That is, each statement in braces will be executed . - return
return The following expression is the return value of the function . When a function runs to return when , The function will exit , The statement after the function will not run , When a function does not return when , Then the function will exit when it runs to a valid executed statement before the anti bracket in the brace .
Knowledge points supplement :
- The arguments of the function when it is called are arguments , The parameters in the function brackets are formal parameters , Function is called , The argument will assign a value to the formal parameter .
- If the definition of the function is written in main() After the function , You need to declare the function first , Written in main() Function does not need to be declared before .
- The declaration of a function can be placed anywhere in front of the function call . It can even be placed in main() In the function , But it's not recommended .
- When a formal parameter is passed in the form of an array , In fact, the essence is to pass the pointer . When passing an array as an argument , In fact, the first address of the array of arguments is passed , Therefore, if we want to access all the variables of the array in the function, we need to pass the number of array elements . Because it is passed as a pointer , Therefore, the formal parameter array is sizeof The operation size is only 4 byte , This also explains why the number of array elements must be passed when passing an array .
2.2 A profound
Implement a function through the above explanation . requirement : Find the factorial of a number .
Source code :
#include <stdio.h>
/* Function declaration */
int sum_func(int n);
int main()
{
int data = 0;
int sum = 0;
printf("please input a num: ");
scanf("%d", &data);
while (data < 0) {
printf("input errror! please input again: ");
scanf("%d", &data);
}
sum = sum_func(data); //data For reference
printf("%d! = %d\n", data, sum);
return 0;
}
/* The return value type of the function is int. The function name is sum_func A function has only one parameter , Formal parameters are int type . */
int sum_func(int n)
{
int i = 1, sum = 1;
if (n < 0) {
return -1;
} else if (n == 0) {
return 1;
} else {
while (i <= n) {
sum *= i;
i++;
}
}
return sum;
}
Running results :
please input a num: -1
input errror! please input again: -10
input errror! please input again: 5
5! = 120
Two 、 Parameter passing of function
The parameters of a function can be transferred in two cases :
- Value passed
- Address delivery
When the function is called , Will pass arguments to formal parameters , Formal parameter is a new space , If it is time to pass values , Change the value of parameter , The value of an argument cannot be changed , But if it's address passing , Because of the nature of the pointer , If you change the value of the address in the formal parameter, the argument will be changed . In fact, it's plain , The essence of value passing and address passing is that formal parameters and actual parameters perform an assignment operation .
Let's take a look at the following program , Look at that function to change main The value in the function .
Source code :
#include <stdio.h>
void exchange_func_1(int a, int b)
{
int t;
t = a;
a = b;
b = t;
}
void exchange_func_2(int *a, int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
}
int main()
{
int a = 3, b = 4;
exchange_func_1(a, b); // Value passed
printf("exchange_func_1: a = %d, b = %d\n", a, b);
exchange_func_2(&a, &b); // Address delivery
printf("exchange_func_2: a = %d, b = %d\n", a, b);
return 0;
}
Running results :
exchange_func_1: a = 3, b = 4
exchange_func_2: a = 4, b = 3
For the above operation results , The first thing to be clear is main Variables in functions a,b and exchange_func_1() exchange_func_2() The variables in these two a , b It is different in memory space , This point has been explained in the theory section above , Because the formal parameters are reopened memory , On function call , Only one assignment operation is performed . So when passing values , change exchange_func_1() The variables in the a,b,main() Variables in functions a,b It doesn't change . During address transfer , because exchange_func_2() in a, b This is the point main() Function a, b The address of , Through the value operator , You can manipulate the contents of the address . therefore exchange_func_2() The function can change main() Variable in function a,b The value of the .
3、 ... and 、 Recursive function
Recursive function refers to the function body of a function that directly or indirectly calls the function itself .
The execution of recursive function calls is divided into two stages :
Recurrence stage : Starting from the original question , Recursion from unknown to known according to recursive formula , Finally, the recursive termination condition is reached
The stage of return : Find the result according to the recursive termination condition , Reverse step-by-step substitution into recursive formula , Return to the original problem solving
Source code ( Recursive implementation of factorial ):
#include <stdio.h>
int recursion_func(int a)
{
int i = a;
if (a <= 1) {
return 1;
} else {
return a * recursion_func(a - 1);
}
}
int main()
{
int data = 0;
int sum = 0;
printf("please input a num: ");
scanf("%d", &data);
while (data < 0) {
printf("input errror! please input again: ");
scanf("%d", &data);
}
sum = recursion_func(data);
printf("%d! = %d\n", data, sum);
return 0;
}
Running results :
please input a num: -1
input errror! please input again: -10
input errror! please input again: 5
5! = 120
Recurrence stage :
recursion_func(5) = 5 * recursion_func(4)
recursion_func(4) = 4 * recursion_func(3)
recursion_func(3) = 3 * recursion_func(2)
recursion_func(2) = 2 * recursion_func(1)
recursion_func(1) = 1
The stage of return :
recursion_func(1) = 1
recursion_func(2) = 2 * recursion_func(1) = 2 * 1 = 2
recursion_func(3) = 3 * recursion_func(2) = 3 * 2 = 6
recursion_func(4) = 4 * recursion_func(3) = 4 * 6 = 24
recursion_func(5) = 5 * recursion_func(4) = 5 * 24 = 120
When the function runs to recursion_func(5) when , It needs to run because the conditions are met recursion_func(4), function recursion_func(4) when , And because the conditions are met recursion_func(3), Until recursion_func(1) Can return a specific value , here recursion_func(2) Because recursion_func(1) The function will not run until the specific value is returned , And so on until recursion_func(5). like this , When this recursive function is called externally , There will be a recurrence phase and a regression phase . Therefore, we will also find a drawback of recursive functions , In the recursive phase, only when the deepest layer returns a specific value , Will release the stack space opened up by the previous function in turn . That is, it runs in the recursive phase recursion_func(5) when ,recursion_func(5) If the stack space occupied by the function is not released, it will be called recursion_func(4) Take up stack space again , Until recursion_func(1). That is to say The recursive phase will always open up stack space , Only in the regression phase can stack space be released in turn , If the recursion level is too deep , This will result in insufficient stack space , Therefore, the efficiency of recursive functions is relatively low , But in some special situations, recursive function is a good choice .
边栏推荐
- 发射,接收天线方向图
- ICML 2022:ufrgs | optimistic linear support and subsequent features as the basis for optimal strategy transfer
- C language character pointer and string initialization
- SQL中IS NOT NULL与!=NULL的区别
- Course strategy sharing plan of Zhejiang University
- 【AI应用】NVIDIA Tesla V100S-PCIE-32GB的详情参数
- Use of go log package log
- 使用cef3开发的浏览器不支持flash问题的解决
- What if Fiddler fails to listen to the interface
- 新加坡国立大学|采用无模型强化学习方法评估能源效益数据中心的节能情况
猜你喜欢

C WinForm reads the resources picture

fiddler 监听不到接口怎么办

vivado 如何添加时序约束
![[tinyriscv verilator] branch transplanted to Da Vinci development board of punctual atom](/img/a8/4786e82d0646b08c195dd0a17af227.png)
[tinyriscv verilator] branch transplanted to Da Vinci development board of punctual atom

【IDEA】IDEA 格式化 代码技巧 idea 格式化 会加 <p> 标签

Discuz small fish game wind shadow legend business gbk+utf8 version template /dz game website template

跨系统数据一致性问题解决方案汇总

vivado VIO IP的用法

c语言之字符串数组

The latest cloud development wechat balance charger special effect applet source code
随机推荐
ICML 2022:ufrgs | optimistic linear support and subsequent features as the basis for optimal strategy transfer
[learn FPGA programming from scratch -48]: Vision - development and application of intelligent sensors
pytorch基础(1)
golang使用mongo-driver操作——查(基础)
【AI应用】NVIDIA Tesla V100S-PCIE-32GB的详情参数
2022年PMP项目管理考试敏捷知识点(3)
c语言之字符串数组
支持删除,更新任意结点的优先级队列
C# Winform 读取Resources图片
通过 MQTT 检测对象和传输图像
C language - date formatting [easy to understand]
webserver流程图——搞懂webserver各模块间调用关系
fiddler 监听不到接口怎么办
Const keyword and its function (usage), detailed explanation of C language const
如何设置企业微信群机器人定时发消息?
使用cef3开发的浏览器不支持flash问题的解决
First principles (optimal solution theory)
One step forward is excellent, one step backward is ignorant
MySQL删除表后如何使ID从1开始
圖的存儲結構