当前位置:网站首页>C language series - Section 3 - functions
C language series - Section 3 - functions
2022-07-03 04:17:00 【Unity of knowledge and practice, come on】
function
1. What is a function ?
Wikipedia definition of function :
In computer science , Subroutines ( English :Subroutine, procedure, function, routine, method, subprogram, callable unit), It's a piece of code in a large program , Consists of one or more statement blocks . It's responsible for a particular task , And compared to other generations code , With relative independence .
Generally, there will be input parameters and return values , Provide encapsulation of the process and hiding of details . These codes are usually integrated into software libraries .
2. C Classification of functions in language :
Library function
Custom function
2.1 Library function :
Why are there library functions ?
- We know that in our study C In language programming , Always can't wait to know the result after a code is written , Want to
Print this result on our screen and see . At this time, we will frequently use a function : Put the information in a certain grid
Print to the screen (printf).- In the process of programming, we will frequently copy some strings (strcpy).
- In programming, we also calculate , Always calculate n Of k Such an operation to the power (pow).
Like the basic functions we described above , They are not business code . In our development process, every programmer may use , In order to support portability and improve program efficiency , therefore C A series of similar library functions are provided in the basic library of the language , It is convenient for programmers to develop software .
So how to learn library functions ?
www.cplusplus.com(c Language official website query library function )
A brief summary ,C The library functions commonly used in the language are :
1.IO function
2. String manipulation functions strlen strcpy str
3. Character manipulation functions
4. Memory manipulation function
5. Time / Date function
6. Mathematical functions
6. Other library functions
We refer to the documentation , Learn several library functions :( Teach how to use documents to learn library functions ).
strcpy
notes :
But a secret that library functions must know is : Use library functions , Must contain #include Corresponding header file .
Here, learn the above library functions by referring to the documentation , The purpose is to master the use of library functions
2.2 Custom function
If library functions can do everything , What do programmers do ?
All the more important is custom functions .
Custom functions are the same as library functions , There's a function name , Return value types and function parameters .
But the difference is that these are all designed by ourselves . This gives programmers a lot of room to play .
Composition of functions :
ret_type fun_name(para1, * )
{
statement;// Statement item
}
ret_type Return type
fun_name Function name
para1 Function parameter
Let's give you an example :
` Write a function to find the maximum value of two integers .
#include <stdio.h>
//get_max Function design
int get_max(int x, int y) {
return (x > y) ? (x) : (y);
}
int main()
{
int num1 = 10;
int num2 = 20;
int max = get_max(num1, num2);
printf("max = %d\n", max);
return 0;
}
Another example :
Write a function to exchange the contents of two shaping variables .
#include <stdio.h>
// Implemented as a function , But I can't finish the task
// Wrong version ( Cannot change the main function main in num1 and num2 Value )
/* as a result of , In each function , The value created again , Even with another function , A certain value The name is the same , But the addresses used are different , The values represented have different meanings , It can't be in two In different functions , Modify the same value , Unless the transmission is Address ( The pointer )*/
void Swap1(int x, int y) {
int tmp = 0;
tmp = x;
x = y;
y = tmp;
}
// The right version ( It's an address , You can modify the value )
void Swap2(int* px, int* py) {
/* Accept addresses with pointer variables */
int tmp = 0;
tmp = *px;
*px = *py;
*py = tmp;
}
int main()
{
int num1 = 1;
int num2 = 2;
Swap1(num1, num2);
printf("Swap1::num1 = %d num2 = %d\n", num1, num2);
Swap2(&num1, &num2);/*& Symbol Is to take the address symbol , It's an address */
printf("Swap2::num1 = %d num2 = %d\n", num1, num2);
return 0;
}
Supplement the method of modifying values across functions :
1. Directly define global variables ( It can be modified anywhere )
2. When a function passes values , It's the address ( That is, the above method , Speak in detail at the pointer )
3. The parameters of the function
3.1 The actual parameter ( Actual parameters )
The parameters that are actually passed to the function , It's called the actual parameter .
The argument can be : Constant 、 Variable 、 expression 、 Functions, etc .
Whatever the type of argument is , When you make a function call , They all have to have certain values , So that we can send these values to the shape
ginseng .
3.2 Formal parameters ( Shape parameter )
Formal parameters refer to the variables in brackets after the function name , Because formal parameters are only instantiated when the function is called ( Allocate memory units ), So it's called formal parameter . Formal parameters are automatically destroyed when the function call is completed . So formal parameters are only valid in functions .
above Swap1 and Swap2 Parameters in function x,y,px,py Are formal parameters . stay main Function passed to Swap1 Of num1 ,num2 And pass it on to Swap2 Functional &num1 , &num2 Is the actual parameter .
Here we analyze the real and formal parameters of the function :
So we can simply think that : After the formal parameter is instantiated, it is actually equivalent to a temporary copy of the argument .
4. Function call :
4.1 Value transfer call
The formal and actual parameters of a function occupy different memory blocks , Modification of a parameter does not affect the argument .
4.2 Address call
Address call is a way to call a function by passing the memory address of the created variable outside the function to the function parameter .
This parameter transfer method can establish a real relationship between the function and the variables outside the function , In other words, the variables outside the function can be directly manipulated inside the function .
4.3 practice
- Write a function to determine whether a number is a prime .
- Write a function to determine whether a year is a leap year .
- Write a function , To realize binary search of an ordered array .
- Write a function , Every time you call this function , Will be num The value of the increase 1.
answer :
1.
int prime(int i)
{
int j = 0;
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
return 0;
}
}
return 1;
}
2.
int is_leap(int year)
{
if ((year % 4 == 0 || year % 100 ==0) && year % 400 == 0)
{
return 1;
}
return 0;
}
3.
int BinarySearch(int arr[], int size, int tofind){
//[left, right] The interval to be searched
int left = 0;
int right = size - 1;
// if int right = sizeof(arr) / sizeof(arr[0]) - 1;
// Output right = 0, The array will be implicitly converted into a pointer .
while (left <= right){
int mid = (left + right) / 2;
if (arr[mid] < tofind){
// Go to the right section to find
left = mid + 1;//mid This location has been searched
}else if (arr[mid] > tofind){
// Go to the left section to find
right = mid - 1;
}else{
// eureka
return mid;// Returns the subscript of the position
}
}
return -1;//-1 I didn't find
}
4.
void Func(int* x){
*x += 1;
}
5. Nested calls and chained access to functions
Functions and functions can be combined according to actual needs , That is, calling each other .
5.1 Nested calls
In a function , Call another function
#include <stdio.h>
void new_line()
{
printf("hehe\n");
}
void three_line()
{
int i = 0;
for (i = 0; i < 3; i++)
{
new_line();
}
}
int main()
{
three_line();
return 0;
}
Functions can be called nested , But you can't nest definitions .
5.2 Chained access
Take the return value of one function as the parameter of another function .
#include <stdio.h>
#include <string.h>
int main()
{
char arr[20] = "hello";
int ret = strlen(strcat(arr, "bit"));/* Here is an introduction strlen function */
strlen
/*strlen The function is used to calculate , The length of the string , But not \0. The return value is the length */
/* Add :sizeof Is used to calculate the length of the array , It can also be used to calculate , String length , but Yes, it will \0( The string ends with '\0'),*/
strcpy
/*strcpy function , Used to copy strings , The return value is the copied string , Format strcpy(a1,a2)*/
printf("%d\n", ret);
return 0;
}
#include <stdio.h>
int main()
{
printf("%d", printf("%d", printf("%d", 43)));
/* The result is what ?*/ 1234
notes :printf The return value of the function is the character printed on the screen * Number *
return 0;
}
6. Function declaration and definition
6.1 Function declaration
Templates :
Function return value ( No return is void) + The name of the function ( Customize )+ ( Reference value ) ;( A semicolon
Tell the compiler that there is a function called , What are the parameters , What is the return type . But does it exist , Function declarations do not determine .
The declaration of a function usually precedes the use of the function . To satisfy the requirement of declaration before use .
The declaration of the function is usually placed in the header file ,( Here's the explanation )
6.2 Function definition
The definition of a function refers to the concrete implementation of a function , Explain the function realization .
Specific examples :( Write a return a,b And function )
1. First, in the vs Create header files and two source files
2. Declare... In the header file
3. In the function definition source file , Define function purpose
4. stay test Functions used in source files
Add :
.c Represents the source file ( Source files are interconnected )
.h Represents the header file
Interworking in the source file , There is no need to quote each other , But in the header file , It is not interconnected with the source file , It needs to be in the source file , Reference header file #include “ Header file name ”( Double quotes )
7. Function recursion
7.1 What is recursion ?
The programming skill of program calling itself is called recursion ( recursion).
Recursion as an algorithm is widely used in programming languages . A procedure or function has a method that directly or indirectly calls itself in its definition or description , It usually transforms a large and complex problem into a smaller problem similar to the original problem to solve , The recursion strategy only needs a few programs to describe the repeated calculation needed in the process of solving problems , Greatly reduces the amount of code in the program .
The main way to think about recursion is : Turn the big thing into a small one
7.2 Two necessary conditions for recursion
1. There are restrictions , When this constraint is met , Recursion doesn't continue .
2. After each recursive call, it gets closer and closer to this constraint
7.2.1 practice 1
Accept an integer value ( Unsigned ), Print each bit of it in order .
for example :
Input :1234, Output 1 2 3 4
#include <stdio.h>
void print(int n) {
if (n > 9)
{
print(n / 10);
}
printf("%d ", n % 10);
}
int main()
{
int num = 1234;
print(num);
return 0;
}
7.2.2 practice 2
Writing functions does not allow the creation of temporary variables , Find the length of the string .
#incude <stdio.h>
int Strlen(const char* str) {
if (*str == '\0')
return 0;
else
return 1 + Strlen(str + 1);
}
int main()
{
char* p = "abcdef";
int len = Strlen(p);
printf("%d\n", len);
return 0;
}
7.3 Recursion and iteration
Iterations are sequential , Not a recursive
7.3.1 practice 3
Please n Fibonacci Numbers .( Don't think about spillovers )
int fib(int n) {
if (n <= 2)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
But we found something wrong ;
In the use of fib When we use this function, if we want to calculate the number 50 A Fibonacci number is particularly time-consuming .
Use factorial Function finding 10000 The factorial ( Regardless of the correctness of the results ), The program will crash .
Why? ?
We found that fib In fact, many calculations are repeated during the call of a function .
If we change the code :
int count = 0;// Global variables
int fib(int n) {
if (n == 3)
count++;
if (n <= 2)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
Finally, let's output count, Is a very big value .
Then how can we improve ?
In the debug factorial Function , If your parameters are large , That would be an error : stack overflow( Stack overflow ) Such information .
The stack space allocated by the system to the program is limited , But if there's a dead circle , perhaps ( Dead recursion ), This may cause the stack space to be opened up all the time , Finally, the stack space is exhausted , This phenomenon is called stack overflow
How to solve the above problems :
- Rewrite recursion to non recursion .
- Use static Object substitution nonstatic Local objects . In recursive function design , have access to static Object substitution nonstatic Local objects ( The stack object ), This not only reduces the number of calls and returns that are generated and released each time recursively nonstatic Object cost , and static Object can also hold the intermediate state of recursive calls , And it can be accessed by each calling layer
such as , The following code uses , In a non recursive way :
// seek n The factorial
int factorial(int n) {
int result = 1;
while (n > 1)
{
result *= n;
n -= 1;
}
return result;
}
// Please n Fibonacci Numbers
int fib(int n) {
int result;
int pre_result;
int next_older_result;
result = pre_result = 1; while (n > 2)
{
n -= 1;
next_older_result = pre_result;
pre_result = result;
result = pre_result + next_older_result;
}
return result;
}
边栏推荐
- Interaction free shell programming
- JS realizes the animation effect of text and pictures in the visual area
- Export of zip file
- mysql字段userid逗号分开保存按userid查询
- leetcode:297. Serialization and deserialization of binary tree
- MPLS setup experiment
- Interface in TS
- Xrandr modifier la résolution et le taux de rafraîchissement
- eth入门之DAPP
- MongoDB 慢查询语句优化分析策略
猜你喜欢
[home push IMessage] software installation virtual host rental tothebuddy delay
[pat (basic level) practice] - [simple simulation] 1063 calculate the spectral radius
2022deepbrainchain biweekly report no. 104 (01.16-02.15)
JMeter starts from zero (III) -- simple use of regular expressions
CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强
解决bp中文乱码
Database management tool, querious direct download
The latest activation free version of Omni toolbox
Dismantle a 100000 yuan BYD "Yuan". Come and see what components are in it.
540. Single element in ordered array
随机推荐
arthas watch 抓取入参的某个字段/属性
JS realizes the animation effect of text and pictures in the visual area
Social phobia of contemporary young people (III)
Bisher - based on SSM pet adoption center
BMZCTF simple_ pop
类的基础语法
300+ documents! This article explains the latest progress of multimodal learning based on transformer
JMeter starts from zero (III) -- simple use of regular expressions
因子选股-打分模型
js/ts底层实现双击事件
PostgreSQL database high availability Patroni source code learning - etcd class
Data Lake three swordsmen -- comparative analysis of delta, Hudi and iceberg
How do you use lodash linking function- How do you chain functions using lodash?
vim 的实用操作
Mila、渥太华大学 | 用SE(3)不变去噪距离匹配进行分子几何预训练
Redis persistence principle
Basic types of data in TS
MongoDB 慢查询语句优化分析策略
[untitled] 2022 safety production supervisor examination question bank and simulated safety production supervisor examination questions
540. Single element in ordered array