[C Language] Function Detailed Explanation

Table of contents

1. Function definition and function classification

1. Definition of function

2. Classification of functions

2. Library functions and custom functions

1. Library functions

2. Custom functions

3. Function parameters

1. Actual parameters (actual parameters)

 2. Formal parameters (formal parameters)

 Fourth, the function call

1. Call by value

2. Call by address

 5. Nested call and chained access of functions

1. Nested calls of functions

 2. Chain access

 6. Function declaration and definition

1. Function declaration

2. Function definition

Seven, function recursion and iteration

1. What is recursion?

 2. Two necessary conditions for recursion

3. Recursion and iteration 


1. Function definition and function classification

1. Definition of function

Speaking of functions, in mathematics we think of the independent and dependent variables of the function

Among them, the definition of function in Wikipedia is: subroutine

(1) In a computer, 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.

(2) Generally, there are input parameters and return values, which provide the encapsulation of the process and the hiding of details.

2. Classification of functions

(1) Library functions

(2) Custom functions

2. Library functions and custom functions

1. Library functions

(1) What is a library function

When we usually learn C language, we often use functions with some functions, such as printf (formatted output function, the last letter f format) that usually wants to print the result to the screen, obtain keyboard input scanf, and calculate characters strlen for string length.

The ones that complete certain basic functions above are not business codes, but are often used by each of our programmers.

Therefore, in order to improve our usual work efficiency, some similar library functions are provided in the C language basic library, which is convenient for programmers to develop software.

Library functions are generally specified in the C language standard and implemented by compiler manufacturers.

(2) How to learn library functions?

highly recommended

First of all, we enter  www.cplusplus.com  and click REFERENCE  as shown in the figure

In the C Library, you will see that we often use header files such as stdio.h, etc.

 Click to enter, and you will see some commonly used functions in the left column.

Continue to click to see the detailed explanation of the function, as shown in the figure

 A brief summary of library functions: Common library functions:

  • I/O function
  • character operator functions
  • string operator functions
  • memory manipulation function
  • math function
  • time/date functions
  • other functions

Note: When using library functions, be sure to include the header files corresponding to #include, and don't forget

2. Custom functions

A custom function is the same as a function, with a function name , return value type , and function parameters

The definition form of the function

ret_type fun_name(para1, * )
{
statement;//语句项
}
ret_type 返回类型
fun_name 函数名
para1   函数参数
类型说明符 函数名( 形参类型 参数1,形参类型 参数2,......)
{
    stamens;
    //语句项
    
}

(1) [Give an example]

Write a function that finds the maximum of two numbers.

#include <stdio.h>
//get_max函数的设计
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;
}

(2) Another example [here comes the key point]

Write a function that swaps two integer variables

//实现成函数,但是不能完成任务
void Swap1(int x, int y)
{
	int tmp = 0;
	tmp = x;
	x = y;
	y = tmp;
}

int main()
{
	int num1 = 1;
	int num2 = 2;
	Swap1(num1, num2);
	printf("Swap1::num1 = %d num2 = %d\n", num1, num2);
	return 0;
}

Note that there is a problem with the code, there is an error in understanding the parameters, please see the correct code below

#include <stdio.h>
//正确的版本
void Swap2(int* px, int* py)
{
	int tmp = 0;
	tmp = *px;
	*px = *py;
	*py = tmp;
}
int main()
{
	int num1 = 1;
	int num2 = 2;
	Swap2(&num1, &num2);
	printf("Swap2::num1 = %d num2 = %d\n", num1, num2);
	return 0;
}

Next, the parameters of the function explain the parameters in detail.

3. Function parameters

1. Actual parameters (actual parameters)

Actual parameter: The parameter actually passed to the function (that is, the argument in mathematics).

Parameters can be: constants, variables, expressions, functions, etc.

However, when the function is called, they must have a definite value in order to be passed to the formal parameters.

In the above summation code

 2. Formal parameters (formal parameters)

Formal parameters refer to the variables in parentheses after the function name , because formal parameters are only instantiated (allocated memory units) when the function is called, so they are called formal parameters.

Formal parameters are automatically destroyed when the function call completes. Therefore formal parameters are only valid within the function.

 Summary: After the formal parameter is instantiated, it is equivalent to a temporary copy of the actual parameter

 Fourth, the function call

1. Call by value

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

When we write a function, write a function add() that prints the addition of two numbers, then the function call needs two values, here for example pass the sum of 3 and 5, then add(3,5)

2. Call by address

(1) Call by address is a method of calling a function by passing the memory address of the variable created outside the function to the function parameter.

(2) This method of passing parameters can establish a real connection between the function and the variables outside the function, that is, the
variables outside the function can be directly manipulated inside the function.

So in the code above that exchanges two numbers, the function needs to be called by reference to modify the value of the external variable.

(3) Function exercises

1. Write a function to determine whether a number is prime or not.

#include <stdio.h>
int Is_prime(int n) 
{
	int i = 0;
	for (i = 2; i < n;i++)
	{
		if (n%i == 0)
		{
			return 0;//不是素数返回0
		}
	}
	return 1;//for循环完成后,如果是素数返回1
}
int main() 
{
	int n = 0;
	scanf("%d",&n);
	if (Is_prime(n))
		printf("%d is prime", n);
	else
		printf("%d is not prime", n);
	return 0;
}

A prime number is a positive integer that can only be divisible by 1 and itself, so it is not a prime number that can be divisible by other numbers (excluding 1 and itself). To expand, a number is divisible by other numbers.

For example, 16, 16 = 2 * 8; 16 = 4 * 4; 16 = 8 * 2; Here we can see that a number is not a prime number to calculate 2, 4, 8

In fact, it only needs to be calculated   \sqrt[]{16} = 4, because if one of 2*8 and 8*2 satisfies, then it is not a prime number. As far as i <= the square root of a number, i<=  \sqrt[]{n}. According to this principle, the code below is

prime number method two

#include <stdio.h>
#include <math.h>
int Is_prime(int n)
{
	int i = 0;
	for (i = 2; i <=sqrt(n); i++)
	{
		if (n % i == 0)
		{
			return 0;
		}
	}
	return 1;
}
int main()
{
	int n = 0;
	scanf("%d", &n);
	if (Is_prime(n))
		printf("%d is prime", n);
	else
		printf("%d is not prime",n);
	return 0;
}

2. Write a function to determine whether a year is a leap year or not.

#include <stdio.h>
int is_leap_year(int y)
{
	if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
		return 1;
	else
		return 0;

}
int main() 
{
	int y = 0;
	scanf("%d",&y);
	if (is_leap_year(y))
		printf("%d is leap year\n", y);
	else
		printf("%d is not leap year\n",y);

	return 0;
}

Ordinary leap years refer to Gregorian calendar years that are multiples of 4 and not multiples of 100, while century leap years must be multiples of 400.

3. Write a function to implement binary search of an integer sorted array.

#include <stdio.h>
int binary_search(int arr[],int num ,int sz)
{
	int left = 0;
	int right = sz - 1;
	int mid = 0;
	while (left<=right)
	{
		mid = (left + right) / 2; //可以优化为mid = left+(right-left)/2;
		if (arr[mid]>num)
		{
			right = mid - 1;
		}
		else if (arr[mid]<num)
		{
			left = mid + 1;
		}
		else 
		{
			return mid;
		}
	}
	return -1;
}
int main() 
{
	int arr[] = {1,2,3,4,5,6,7,8,9,10};
	int num = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);//数组元素的个数
	scanf("%d",&num);	//输入一个要查找的数
	int ret = binary_search(arr, num, sz);
	if (ret != -1)
		printf("找到了,该数下标为:%d",ret);
	else
		printf("没有找到 !");
	
}

4. Write a function that increases the value of num by 1 each time the function is called.

#include <stdio.h>
void add(int * p)
{
	*p = *p + 1;
}
int main() 
{
	int num = 0;
	add(&num);//调用第一次,调用传的是地址
	printf("%d\n",num);
	add(&num);//第二次
	printf("%d\n",num);
	add(&num);//第三次
	printf("%d\n",num);
	return 0;
}

 5. Nested call and chained access of functions

1. Nested calls of functions

Functions can call each other. Note that functions can be nested, but not nested.

#include<stdio.h>
void test3() 
{
	printf("666\n");
}
void test1() 
{
	int i = 0;
	while (i < 3)
	{
		test3();
		i++;
	}
}
int main() 
{
	test1();
	return 0;
}

 2. Chain access

Use the return value of one function as an argument to another function 

#include <stdio.h>
int main()
{
  printf("%d", printf("%d", printf("%d", 43)));
  //注:printf函数的返回值是打印在屏幕上字符的个数
  return 0;
}

The result is: 4321

 6. Function declaration and definition

1. Function declaration

#include<stdio.h>
int add(int x, int y);
  • 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.
  •  The declaration of a function generally appears before the use of the function. It must be declared before use .
  • Function declarations are generally placed in header files.

2. Function definition

The definition of a function refers to the specific realization of the function, explaining the function realization of the function.

//函数的实现
int add(int x,int y)
{
    return x + y;
}

Seven, function recursion and iteration

1. What is recursion?

recursion + regression

A programming technique in which a program calls itself is called recursion

Recursion is widely used as an algorithm in programming languages.
A process or function has a method of calling itself directly or indirectly in its definition or description . It usually transforms a large and complex problem layer by layer into a smaller-scale problem similar to the original problem to solve, recursive strategy. Only a small number of programs can describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of code in the program. Core idea: make big things small

 2. Two necessary conditions for recursion

  • There are restrictions, and when the conditions meet the restrictions, the recursion stops
  • After each recursion, it is close to this constraint

 [Example] (1) Accept an integer value (unsigned), and print each bit of it in order

#include <stdio.h>
void print(int n)
{
	if (n>9)		//限制条件
	{
		print(n/10);	//每次递归越来越接近这个限制条件
	}
	printf("%d ",n%10);	//打印n 的每一位
}
int main()
{
	int n = 0;
	scanf("%d", &n);
	print(n);
	return 0;
}

 

 Diagram where 5 -> 6 -> 7 -> 8 is the printing order 2 0 2 3 

 [Example] (2) Writing a function does not allow the creation of temporary variables, find the length of the string

#include <stdio.h>
int Strlen(char* str)
{
	if (*str == '\0')
		return 0;
	else
		return 1 + Strlen(str+1);//如果还有字符就继续递归判断下一个字符
}
int main()
{
	char *str = "abc";
	int len = Strlen(str);
	printf("%d\n",len);
	return 0;
}

 【Illustration】 Follow the arrows and steps to watch patiently, and you will gain a lot

3. Recursion and iteration 

Iteration can also be understood as a loop

[Example] Find the nth Fibonacci number (without considering overflow)

Fibonacci numbers 1 1 2 3 5 8 13 21 ...... The first and second numbers are 1, and the latter item is equal to the sum of the first two items

The following code is implemented recursively

#include <stdio.h>
int fib(int n)
{
	if (n <= 2)
		return 1;
	else
		return fib(n - 1) + fib(n - 2);
}
int main()
{
	int n = 0;
	scanf("%d",&n);
	int ret = fib(n);
	printf("%d\n", ret);
	return 0;
}

However, there will be certain problems in writing this way, that is, it takes a long time to calculate the Fibonacci numbers after the 50th, and if you try to find a very large number, stack overflow may occur.

Because the stack space allocated by the system to the program is limited, infinite loops (dead recursion) are prone to occur, which may lead to the continuous
development of stack space, and eventually the stack space will be exhausted. This phenomenon is called stack overflow.

To solve the above problem you can use

  • recursive to non-recursive
  •  Use static objects instead of nonstatic local objects.

The following is a non-recursive way to achieve

#include<stdio.h>
int fib(int n ) 
{
	int a = 1;
	int b = 1;
	int c = 1;
	while (n>2)
	{
		c = a + b;
		a = b;
		b = c;
		n = n - 1;
	}
	return c;
}
int main() 
{
	int n = 0;
	scanf("%d", &n);
	int ret = fib(n);
	printf("%d\n",ret);
	return 0;
}

So usually it is easy to think of recursion, and recursion can be used when there are no obvious bugs.

Guess you like

Origin blog.csdn.net/qq_72505850/article/details/131939330