Elementary C Language | Functions

1. What is a function?

There are many ways to say functions, and the definition of functions in Wikipedia: Subroutines

A subroutine is a certain part of code in a large program, consisting of one or more statement blocks. It is responsible for completing a specific task and is relatively independent from other codes.

Generally, there are parameters and return values, which provide the encapsulation of the process and the hiding of details. These codes are often integrated as software libraries.

2. Classification of functions in C language

2.1 Library functions

The basic functions (printf, strcpy, pow) that every programmer may use during the development process, in order to support portability and improve program efficiency, C language has a series of similar functions, It is convenient for programmers to carry out software development.

You can learn the use of library functions through this link:

https://cplusplus.com

insert image description here

The library functions can be summarized into 6 types:

IO function (input and output function) scanf printf …

String manipulation functions issupper ...

The memory manipulation function memset ...

time/date functions time …

Mathematical functions sqrt pow …

Other library functions...

We refer to the documentation to learn several library functions
strcpy (copy string)
in the form of char * strcpy ( char * destination, const char * source );
destination
source source
as shown in the figure:
insert image description here
menset (filling memory block)
in the form of void * memset ( void * ptr, int value, size_t num );
as shown in the figure:
insert image description here

Note: To use library functions, the header files corresponding to #include must be included.

2.2 Custom functions

Of course, library functions cannot implement all functions, so more important is custom functions, such as comparing the maximum value of two numbers

#include <stdio.h>
int max(int x, int y)
{
    
    
	return (x > y) ? x : y;//若x>y条件为真返回x,否则返回y
}
int main()
{
    
    
	int a = 0;
	int b = 0;
	scanf("%d%d", &a, &b);
	int ret=max(a,b);//将实参a和b传给形参x,y,并将自定义函数返回的值赋给变量ret
	printf("%d", ret);
	return 0;
}

Input 2 and 3, output maximum value 3
insert image description here

Another example is the custom function to exchange two numbers

int swap(int* x, int* y)
{
    
    
	int temp = *x;
	*x = *y;
	*y = temp;//*解引用操作符,通过地址直接找到实参的值,然后才改变实参的值
}
int main()
{
    
    
	int a = 0;
	int b = 0;
	scanf("a=%d b=%d", &a, &b);//这里要使用&,将a和b的地址传过去,注意的是在自定义实现函数中,仅仅改变形参是不会影响实参的,所以就要通过地址来直接改变实参的值
	int ret = swap(&a, &b);
	printf("a=%d b=%d", a, b);
	return 0;
}

Input a=2 b=3 output exchanged a=3 b=2
insert image description here

3. Function parameters

3.1 Actual parameters

The parameters actually passed to the function are called actual
parameters. The actual parameters can be: constants, variables, expressions, functions, etc. Note: No matter what type of quantity the actual parameters are, they must have definite values
​​when the function is called , so that these values ​​can be transferred to the formal parameters

3.2 Formal parameters

Formal parameters refer to the variables in parentheses after the function name
Note: Formal parameters are only instantiated (allocated memory space) when the function is called, so they are called formal parameters. When the formal parameters are called, the allocated space will be automatically destroyed. Therefore formal parameters are only valid in custom functions.
In this way, we can see why the case of the exchange example above should be passed in the form of an address instead of a direct value.
Now we analyze the actual parameters and formal parameters of the function:
insert image description here
insert image description here

By comparing the two figures, we can find that passing by value is different from passing by address, so we can simply think that after the formal parameter is instantiated, it is actually equivalent to a temporary copy of the actual parameter.

Fourth, the function call

4.1 Call by value

The formal parameters and actual parameters of the function occupy different memory spaces, and the modification of the formal parameters will not affect the actual parameters.

4.2 Call by address

Call by address is a way of calling functions by passing variables and memory addresses created outside the function to function parameters.
This method of passing parameters allows the function to establish a real connection with the variables outside the function, that is, the function can directly manipulate the external variables.

The call of the two is shown in the above code for exchanging two numbers.

5. Nested call and chained access of functions

Functions and functions can call each other

5.1 Nested calls

Example: To achieve the sum of two numbers

#include <stdio.h>
int Add_1(int x, int y)
{
    
    
	return x + y;//将值返回给函数Add_1
}
int Add(int x, int y)
{
    
    
	return Add_1(x, y);//将函数Add_1的值返回给Add
}
int main()
{
    
    
	int a = 2;
	int b = 3;
	int c=Add(a,b);
	printf("%d", c);
	return 0;
}

Note: Functions can be called nestedly, but not defined nestedly!

5.2 Chain access

For example:

int main()
{
    
    
	int a = 2;
	printf("%d ", printf("%d ", printf("%d ", a)));//printf的返回值是在屏幕上打印的字符的个数
	return 0;
}

The access sequence and how to print it are as follows:
insert image description here
so the result is:insert image description here

6. Function declaration and definition

6.1 Function declaration

1 Tell the compiler what a function is called, what its parameters are, and what its return type is. But whether it exists or not, the function declaration cannot decide.
2. The declaration of the function generally appears before the use of the function. Satisfy the declaration before use.
3. The declaration of the function is generally placed in the header file. Suffix in the form of .h, for example: #include game.h

int menu(); 这就是一个函数声明形式,返回类型为整形,函数名为menu,参数为空,注意声明是一条语句需要加分号。
void caf();
int nba(int x,int y);//此声明多了参数

6.2 Function definition

int menu()
{
    
    
    int a=0;
    int b=0;
    return a+b;
}//这一部分是函数的定义,其包括了函数的声明,可以说函数的定义是一种特殊的函数声明
int main()
{
    
    
   int c=menu();
   printf("%d",c);
   return 0;
}

Seven, function recursion

7.1 What is function recursion

As an algorithm, recursion means that a process or function has a method of directly or indirectly calling itself in its definition or description, which can reduce the size of the program and reduce the amount of code in the program.

7.2 Two Necessary Conditions for Recursion

. There are restrictions. When the restrictions are met, the recursion will not continue.
. After each recursive call, it gets closer and closer to this limit.

7.2.1 A recursive exercise and diagram

void print(int x)
{
    
    
	if (x > 9)
	{
    
    
		print(x / 10);
	}
	printf("%d ", x % 10);
}
int main()
{
    
    
	int num = 1234;
	print(num);
	return 0;
}

Here is an illustration of the recursion of the subfunction:
insert image description here
the final print result is:insert image description here

7.3 Recursion and iteration

7.3.1 What is iteration

Iteration is the process of repeatedly performing an operation through a loop. The iteration does not involve the function call itself, each iteration will be calculated based on the result of the previous iteration, and the result will be updated continuously. Iteration is suitable for solving most problems, and is usually better than recursion in performance, because iteration does not cause excessive growth of the function call stack.

7.3.2 Comparing the difference between recursion and iteration

The factorial of n:

int mul(int n)
{
    
    
	if (n <= 1)
		return 1;
	else
		return n * mul(n - 1);
}
int main()
{
    
    
	//n的阶乘
	int n = 0;
	scnaf("%d", &n);
	int a=mul(n);
	printf("%d", a);
	
	return 0;
}

Fibonacci sequence:

int fin(int x)
{
    
    
	if (x <= 2)
		return 1;
	else
		return fib(x - 2) + fib(x - 1);
}
int main()
{
    
    
	int a = 0;
	scanf("%d", &a);
	int b = fib(a);
	printf("%d", b);
	return 0;
}

The above two use recursion to solve the factorial and Fibonacci sequence of n, but when the value of n is large enough and the value of a is large enough, you will find that recursion is constantly opening up space, which is particularly time-consuming, and even a stack appears overflow. The above results can be carried out in an iterative manner.
The factorial of n:

int main()
{
    
    
	int a = 0;
	scanf("%d", &a);
	int sum = 0;
	while (a > 1)
	{
    
    
		sum *= a;
		a -= 1;
	}
	printf("%d", sum);
	return 0;
}

Fibonacci sequence:

int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	int a = 1;
	int b = 1;
	int c = 0;
	while (n > 2)
	{
    
    
		c = a + b;
		a = b;
		b = c;
		n -= 1;
	}
	printf("%d", c);
	return 0;
}

Tips:
1. Many problems are explained in a recursive form, just because it is clearer than the non-recursive situation
2. However, the iterative implementation of these problems is often more efficient than the recursive implementation, although the code is slightly more readable Worse
3. When a problem is quite complex and difficult to implement iteratively, the simplicity of recursive implementation can compensate at this time.
end~

Guess you like

Origin blog.csdn.net/weixin_68201503/article/details/130627905