当前位置:网站首页>Section 3 - functions

Section 3 - functions

2022-06-13 04:47:00 Stretch the curtain with the wind

Catalog

1. What is a function

2.c Classification of functions in language

2.1. Library function

2.1.1. How to learn to find library functions

 2.1.2. Some library function demonstrations  ( Reference document , Learn several library functions )

2.2. Custom function

2.2.1. Custom function introduction

2.2.2. Function application examples (※)

3. The parameters of the function

3.1. The actual parameter ( Actual parameters )

3.2. Formal parameters ( Shape parameter )

4. Function call

4.1.  Value transfer call

4.2.  Address call

4.3. practice (※)

5. Nested calls and chained access to functions

5.1. Nested calls

5.2 Chained access

6. Function declaration and definition

6.1. Function declaration and definition

6.2. Function code written in actual project

7. Function recursion

7.1. What is recursion

7.2. Two necessary conditions for recursion ( practice )(※)

7.3. Recursion and iteration ( practice )(※)

 8. Several classic topics of function recursion ( Independent research )(※)


1. What is a function

We often see the concept of function in Mathematics . But you know C Functions in language ?
Wikipedia definition of function : Subroutines
In computer science , Subroutines ( English :Subroutine, procedure, function, routine, method,
subprogram, callable unit), It's a piece of code in a large program , A group of one or more statement blocks become . It's responsible for a particular task , And compared to other 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 Parts library .

2.c Classification of functions in language

1. Library function
2. Custom function

2.1. Library function

2.1.1. How to learn to find library functions

Why are there library functions ?
1. We know that in our study C In language programming , Always can't wait to know the result after a code is written , I want to print this result on our screen to see . At this time, we will frequently use a function : Print the information to the screen in a certain format (printf).
2. In the process of programming, we will frequently copy some strings (strcpy).
3. 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 .
Library function details we can see the website :( These websites are related to MSDN be similar )
cppreference.com( English version )
cppreference.com( Chinese translation )
There are many header files in the first website , Click the start file to see the library functions contained in each header file , Open a library function , We can see from the detailed introduction of this function , Or we can search the function directly .

A brief summary ,C The library functions commonly used in the language are :
IO function
String manipulation functions
Character manipulation functions
Memory manipulation function
Time / Date function
Mathematical functions
Other library functions

 2.1.2. Some library function demonstrations  ( Reference document , Learn several library functions )

1.strlen function

The introduction on the website :

Code example :
notes :
1.size_t It means unsigned integer (unsigned int type ), The return value in the introduction is size_t type , So we use size_t Acceptance is the most standard way of writing .
2.%u Print unsigned integers .
2.strcpy function
MSDN Introduction on :

Code example :

3.memset function
MSDN Introduction on :

  Code example :

 

  notes :memst Medium arr It's an array name , Address representing the first element of the array .

2.2. Custom function

2.2.1. Custom function introduction

If library functions can do everything , What do programmers do ?
So more importantly Custom function .
Custom functions are the same as library functions , Yes Function name , return type and Function parameter .
But the difference is that these are all designed by ourselves . This gives programmers a lot of room to play .

Basic composition :

ret_type fun_name(para1, * )
{
statement;// Statement item
}
ret_type Return type
fun_name Function name
para1     Function parameter
notes :
1. Functions can have no parameters and return values , If you don't need a return value , The return type is void Instead of .
2. Function design should pursue high cohesion and low coupling ( Do your own thing , Try not to have anything to do with other functions )
3. It's not easy to have too many function parameters .
4. When designing functions , Try to release resources by those who apply ( Later on )

2.2.2. Function application examples (※)

1. Write a function to find the maximum value of two integers .

Code :

2. Write a function to exchange the contents of two shaping variables .

Error code :

Debugging of error code :

Correct code :( With the help of a pointer )  

 

notes :

1. From here we can see that , When executing a function , The system will recreate the address for the formal parameter ( Instead of the actual parameter address when calling the function ), The system just assigns the actual parameter value in the function call to the corresponding formal parameter . In the above error code, only x and y The values of the two formal parameters are exchanged , Because it's not the same address , So it doesn't matter a and b Value .

In a nutshell : When the function is called , The actual parameter is passed to the formal parameter , A formal parameter is actually a temporary copy of an argument , Therefore, the modification of formal parameters will not affect the arguments .


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 、 function etc. .
Whatever the type of argument is , When you make a function call , They all have to have certain values , In order to pass these values to the parameter .

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 .

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 , That is, you can directly operate inside the function
As a variable outside the function .

notes :

1. Because the address of the first element of the array is actually passed when transmitting the array , Therefore, when using an array to pass, it is equivalent to an address call .

2. The function of address transfer can be realized by using global variables , But not recommended .

4.3. practice (※)

1. Write a function to determine whether a number is a prime .
2. Write a function to determine whether a year is a leap year .
3. Write a function , To realize binary search of an ordered array .
4. Write a function , Every time you call this function , Will be num The value of the increase 1.
5. With the help of functions : If certain conditions are met (n=5) Output hehe, Otherwise output haha.
Exercises 1:

  Exercises 2:

Exercises 3:

Error code :

Error code run result :

Correct code :

Correct code run results :

notes : Array arr Pass to binary_search When , In fact, the message is arr Address of the first element of the array , When passing parameters to an array like this , The number of such elements must be calculated outside and then passed in .

Exercises 4: 

Correct code 1: 

Correct code 2:

  Correct code 3:

Error code :

Exercises 5:

  notes : Function , If you want the function to end early , By means of return Realization , Code above , Functions with return values use return Add the return value to realize , Having no return value , Just one return And then .


5. Nested calls and chained access to functions

5.1. Nested calls

  notes :

1. The calling relationship is :main Function call three_line,three_line It calls new_line. Functions can be called to each other , Nested call .

2. Functions can be called nested , But you can't nest definitions . Here's the picture Is an example of a nested definition , It's wrong. . All functions must be at the same level .

5.2 Chained access

Take the return value of one function as the parameter of another function .
Knowledge point 1:
As shown in the figure above , The third sentence is a combination of the first two sentences , the strlen The return value of the function is printf The parameters of the function , This is chain access .

Knowledge point 2:

Code :

Running results :

notes : Here's the picture MSDN Yes printf Function introduction ,printf The return value of the function is the number of characters that the function prints on the screen ( If an error occurs during printing , Return a negative number )


6. Function declaration and definition

6.1. Function declaration and definition

Function declaration :
1. 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 .
2. The declaration of a function usually precedes the use of the function . To satisfy the requirement of declaration before use .
3. The declaration of the function is usually placed in the header file .
Function definition :
The definition of a function refers to the concrete implementation of a function , Explain the function realization .

Functions are defined directly before the function is used :

Functions are declared before they are used , Then define after the function is used :
notes :
1. If function definition comes later , It needs to be stated before .
2. If function definition comes later , But it is not stated above , The system will report that the function is undefined , Because compiler processing is from front to back , When he saw add After the function , The compiler will wonder if it has seen add function , If you haven't seen , The compiler will issue a warning (add Function undefined ). Therefore, it is generally recommended to put the function in the front .

6.2. Function code written in actual project

Generally in the project , You won't write code like that , It's a split . So let's create one .h The header file , Create another .c The source file ,.h and .c Together, the files are called a module ( In this case, it is called the addition module ), We put the declaration of the function in .h In the header file , Put the definition of the function in .c In the source file , There will be three files :.h Function declaration file ,.c Function definition file ,.c Function call file where the main function of . At this time in .c The file containing the main function of contains its own .h The header file can be used in this file ( Include your own in double quotation marks , The in the library is enclosed in angle brackets ), As shown in the figure below .
The process : A company doesn't write add The code needs to be written by a programmer , So programmers need to write add.c Document and add.h File and then encrypt the static library of the project where the two files are located ( The binary ), then add.h The header file ( The header file is equivalent to the specification , Let the company know what the function parameters are , Know how to use this function ) And static library encryption add.lib Documents are sold to the company ( Can't sell add.c file , If you sell add.c file , Companies know the function implementation code , Programmers can't sell to other companies ), Company import add.h Documents and declarations add.lib File with its own main function code can be achieved .

 1. The code the programmer has to write :

2. The programmer will the project (add.c and add.h file ) Compile into a static library (add.lib), At this point, in the project folder Debug There will be a... In the folder add.lib file , This is the static library .

3. take .h and .lib Documents are sold to the company

4. The company opens the file where its main function is located , Import purchased .h file , And enter the command #pragma comment(lib,"add.lib") To import static libraries , At this point, the function declaration header file #include"add.h" You can use this function .

7. Function recursion

7.1. What is recursion

The programming skill of program calling itself is called recursion ( recursion), Function calling itself is function recursion .
Recursion as an algorithm is widely used in programming languages . A procedure or function has the function of directly or indirectly calling itself in its definition or description A method for the , 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

  Simple recursive code ( It's recursive code , But it will die ):

Running results : Dead cycle ( The program in the figure crashed , So stop )

Error reporting of procedures :

notes :stack overflow Stack overflow means stack overflow , Very common errors in recursive code .

7.2. Two necessary conditions for recursion ( practice )(※)

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 .
notes : If the condition is not met, it will recurse wirelessly , Stack overflow occurs .

Exercise one :

Receive an integer value ( Unsigned ), Print each bit of it in order .
for example :
Input :1234          Output :1 2 3 4

Code :

Graphic interpretation :

notes :

1.%u Stands for unsigned integer .

2. If there is no if Statement restrictions , It will be the same as the one in front main equally , Infinite recursion , Last appearance Stack overflow (stackoverflow) The phenomenon of , Cause the program to crash .( There is a foreign website called stackoverflow Equivalent to the programmer's knowledge , If you don't know, you can ask questions on it )Stack Overflow - Where Developers Learn, Share, & Build Careers

Stack overflow : Each function call will request a space in the stack area of memory , If wireless recursion goes on , Stack space will be used up , No space can be opened up , There will be stack overflow .

  Exercise 2 :

Writing functions does not allow the creation of temporary variables , Find the length of the string .( It means to write a function to realize the function strlen Function functions )

Code 1:( In fact, this code creates count Temporary variable , Does not meet the requirements of the topic )

Code 2: ( The code that conforms to the meaning of the question )

Code 2 Graphic interpretation :

notes :
1. The array name is the address of the first element of the array .
2. In this function ,char The defined character type takes up one byte , So it's a pointer s++; If it's an integer , You need a pointer s+=4; If it is double, You need a pointer s+=8. 

7.3. Recursion and iteration ( practice )(※)

Exercise one :
seek n The factorial .( Don't think about spillovers )
Iterative implementation code :

Recursively implemented code :

Exercise 2 :
Please n Fibonacci Numbers .( Don't think about spillovers )
Fibonacci number :1 1 2 3 5 8 13 21 34 55......
Iterative implementation code :
Recursively implemented code :

notes : Here the recursive system repeats many calculations , Efficiency is very low , For example, below , Computation first 40 individual Fibonacci number of hours , The third Fibonacci number is calculated 39088169 Time .


 8. Several classic topics of function recursion ( Independent research )(※)

1. The hanotta problem     
2. The problem of frog jumping on the steps

8.1. The hanotta problem

subject :
It's said that in the ancient temple of India , There is one called the Hanoi Tower (Hanoi) The game of . The game is on a copper device , There are three rods ( Number A、B、C), stay A From the bottom up 、 Place in order from large to small 64 A gold plate ( Pictured 1). The goal of the game : hold A All the gold plates on the pole are moved to C On the pole , And still keep the original order . Operating rules : Only one plate can be moved at a time , And keep the big plate down all the time during the moving process , Small in , The plate can be placed during the operation A、B、C On any pole .

Code :

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

void move(char pos1, char pos2)
{
	printf("%c->%c  ", pos1, pos2);
}

void Hanoi(int n, char pos1, char pos2, char pos3)
{
	if (n == 1)
	{
		move(pos1, pos3);
	}
	else
	{
		Hanoi(n - 1, pos1, pos3, pos2);
		move(pos1, pos3);
		Hanoi(n - 1, pos2, pos1, pos3);
	}

}

int main()
{
	int n = 0;
	printf(" Please enter the number of plates :");
	scanf("%d", & n);
	Hanoi(n, 'A', 'B', 'C');
	return 0;
}

Running results :

analysis :

From this question we can see , In the case of the tower of Hanoi :A The rod is the starting rod ,B The rod is a transfer rod ,C The pole is the target pole .

When A On 1 null :A->C
When A On 2 null :A->B    A->C    B->C
When A On 3 null :A->C    A->B    C->B    A->C    B->A    B->C    A->C
It can be seen that all mobile ideas are : When there is n(n \geqslant2) null , There are three steps , as follows :
First step : take n-1 A plate from the pole A Through bar C( here C It's a transfer lever ) Move to lever B
The second step : take A A plate on the moves to the pole C
The third step : take n-1 A plate from the pole B( here B Is the starting rod ) Through bar A( here A For the transfer rod ) Move to lever C

8.2. The problem of frog jumping on the steps

subject :
A frog can jump up at a time 1 Stepped steps , You can jump on it 2 level . Ask the frog to jump on one n How many jumps are there in the steps ?( Different results are calculated according to different order ).

Code :

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

int fib(int n)
{
	if (n == 1)
		return 1;
	else if (n == 2)
		return 2;
	else
		return fib(n - 1) + fib(n - 2);

}

int main()
{
	int n = 0;
	printf(" Please enter the order :");
	scanf("%d", &n);
	int s = fib(n);
	printf(" All in all %d Jump \n", s);
	return 0;
}

Running results :

analysis :

To put it another way , It's a number n, Let go 1 and 2 Formed by different arrangements . Due to the influence of arrangement order , For slightly larger n Come on , There are many kinds .


n=1, Only One Jump ,[1].
n=2, So there are two Jump ,[2],[1,1].
n=3, So there are 3、 ... and Jump ,[1,1,1],[1,2],[2,1].
n=4, So there are 5、 ... and Jump ,[1,1,1,1],[1,1,2],[1,2,1],[2,1,1],[2,2].
n=5, So there are 8、 ... and Jump ,[1,1,1,1,1],[1,1,1,2],[1,1,2,1],[1,2,1,1],[2,1,1,1],[2,2,1],[2,1,2],[1,2,2].

We found that , When n Add... In turn 1 when , Its combinatorial number just constitutes a Fibonacci sequence ( That is, the size of a certain number , Equal to the sum of the two preceding numbers ).

Depth analysis :

hypothesis n A stair , Yes f(n) Seed walking method . Frogs can jump for the first time 1 A step or 2 A stair , If you jump one step, you'll be left with n-1 There are steps f(n-1) Seed walking method , jump 2 One step left n-2 There are steps f(n-2) Seed walking method .

Introduction : go n There are... Steps in total f(n-1)+f(n-2) Seed walking method .

Add :

For similar problems : A frog can jump up at a time 1 Stepped steps , You can jump on it 2 level , You can jump on it 3 level . Ask the frog to jump on one n How many jumps are there in the steps ?
analysis :
n=1, One Jump
n=2, two Jump
n=3, Four Jump
n=4, 7、 ... and Jump
We found that , Start with the fourth number , The latter number is the sum of the first three numbers
Code :
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

int fib(int n)
{
	if (n == 1)
		return 1;
	else if (n == 2)
		return 2;
	else if (n == 3)
		return 4;
	else
		return fib(n - 1) + fib(n - 2) + fib(n - 3);

}

int main()
{
	int n = 0;
	printf(" Please enter the order :");
	scanf("%d", &n);
	int s = fib(n);
	printf(" All in all %d Jump \n", s);
	return 0;
}
原网站

版权声明
本文为[Stretch the curtain with the wind]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280520088802.html