当前位置:网站首页>C language function

C language function

2022-07-26 05:10:00 A Liang joy

Catalog

What is a function ?

C Classification of functions in language  

1. Library function  

2. Custom function

The parameters of the function  

1. The actual parameter ( Actual parameters )

2. Formal parameters ( Shape parameter )

Function call

1. Value transfer call

2. Address call

3. practice  

Nested calls and chained access to functions  

1. Nested calls

2. Chained access

Function declaration and definition

1. Function declaration

2. Function definition

  Function recursion

1. What is recursion

2. Two necessary conditions for recursion

3. Recursion and iteration  

Conclusion  


What is a function ?

  When learning mathematics , We often encounter functions , such as y=2x+1 etc. . Actually ,C Language also has the concept of function , 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 , By one or more statements         Block composition . 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 .

C Classification of functions in language  

1. Library function 
2. Custom function 

1. Library function  

Why library functions

1. We know that in our study C In language programming , Always can't wait to know after a code is written       result , I want to print this result on our screen to see . At this time, we will frequently use a function : take       The information is printed on 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 .  Without these library functions , It will lead to low development efficiency 、 There is no unified standard and it is easy to get out bug The problem of . stay C In the standard of language , Given the function name of the library function 、 function 、 Parameters and return types , Then the implementation of library functions is handed over to the compiler manufacturer .

  The blogger here recommends a website for learning library functions :http://www.cplusplus.com .

  To summarize briefly ,C The library functions commonly used in language are :

  • IO function
  • String manipulation functions
  • Character manipulation functions
  • Memory manipulation function
  • Time / Date function
  • Mathematical functions
  • Other library functions

  Be careful : Use library functions , Compulsory includes #include Corresponding header file .

  We don't need to remember all the library functions , But we just need to know how to use it when we use it .

2. Custom function

  In fact, library functions can only help us solve some problems , But it can't solve all the problems . If library functions can solve all problems , What do programmers do ? Therefore, it is more important to customize 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 

  for instance : Write a function to exchange the contents of two integer variables .

Code example :

#include <stdio.h>
// Implemented as a function , But I can't finish the task 
void Swap1(int x, int y)
{
	int tmp = 0;
	tmp = x;
	x = y;
	y = tmp;
}
// The right version 
void Swap2(int* px, int* py)
{
	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);
	printf("Swap2::num1 = %d num2 = %d\n", num1, num2);
	return 0;
}

Output results : 

The parameters of the function  

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 , In order to pass these values to the parameter .

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 All are Formal parameters . stay main Function passed to Swap1 Of num1 ,num2 And pass it on to Swap2 Functional &num1 , &num2 yes The actual parameter

   Here we analyze the real and formal parameters of the function :

  We can see Swap1 When the function is called , x , y Have your own space , As like as two peas, the same thing is true. . So we can simply think that : After the formal parameter is instantiated, it is actually equivalent to a temporary copy of the argument . 

Function call

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 .

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 .

3. practice  

Write a function to determine whether a number is a prime

Code example :

#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 i = 0;
	for (i = 100; i <= 200; i++)
	{
		if (is_prime(i) == 1)
		{
			printf("%d ", i);
		}
	}
	return 0;
}

Write a function to judge whether a certain year is a leap year  

#include <stdio.h>
int is_year(int n)
{
	return (((n % 4 == 0) && (n % 100 != 0)) || (n % 400 == 0));
}

int main()
{
	int year = 0;
	for (year = 1000; year <= 2000; year++)
	{
		if (is_year(year) == 1)
		{
			printf("%d ", year);
		}
	}
	return 0;
}

Write a function to realize the binary search of an integer ordered array  

#include <stdio.h>
//int binary_search(int* arr, int k, int sz)
int binary_search(int arr[], int k, int sz)
{
	int left = 0;
	int right = sz-1;
	while (left<=right)
	{
		int mid = left + (right - left) / 2;
		if (arr[mid] > k)
		{
			right = mid - 1;
		}
		else if (arr[mid] < k)
		{
			left = mid + 1;
		}
		else
		{
			return mid;// eureka 
		}
	}

	return -1;// Can't find 
}

int main()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int sz = sizeof(arr) / sizeof(arr[0]);// Calculate the number of elements of the array and then pass it to the function of binary search 
	// It is impossible to find sz
	int k = 7;
	// Found return subscript ,0~9
	// No return found  -1
	// Array parameters , What is passed is the address of the first element of the array 
	int ret = binary_search(arr, k, sz);

	if (-1 == ret)
		printf(" Can't find \n");
	else
		printf(" eureka , The subscript is :%d\n", ret);

	return 0;
}

Nested calls and chained access to functions  

1. Nested calls

Code example :

#include <stdio.h>
void new_line()
{
	printf("zhangjoy\n");
}
void three_line()
{
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		new_line();
	}
}
int main()
{
	three_line();
	return 0;
}

  Be careful : Functions can be called nested , But you can't nest definitions . 

2. Chained access

Code example :

#include <stdio.h>
int main()
{
  printf("%d", printf("%d", printf("%d", 43)));
  // The result is what ?
  // notes :printf The return value of the function is the number of characters printed on the screen 
  // analysis : Print first 43, then printf The return value of the function is 2, And then print it 2,
  //printf The return value of the function is 1, Finally print 1
  // So the output is :4321
  return 0;
}

  printf The prototype of the function is as follows : 

int printf ( const char * format, ... );

Output results : 

Function declaration and definition

1. Function declaration

  •   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 meet the Declare before use .
  •   The declaration of the function is usually placed in the header file .

2. Function definition

The definition of a function refers to the concrete implementation of a function , Explain the function realization . 

    In Internet companies , Functions are often implemented in modules . As shown below :

Add.h

#include <stdio.h>
int Add(int x, int y);

Add.c 

#include "Add.h"
int Add(int x, int y)
{
	return x + y;
}

Test.c 

int main()
{
	int x = 0;
	int y = 0;
	printf(" Please enter two integers :>");
	scanf("%d%d", &x, &y);
	Add(x, y);
	return 0;
}

  Function recursion

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 .

2. Two necessary conditions for recursion

  • There are restrictions , When this constraint is met , Recursion doesn't continue .
  • After each recursive call, it gets closer and closer to this constraint .

  Be careful : The above two conditions , Any condition is missing , It is possible to form dead recursion .

practice

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

Code example : 

#include <stdio.h>
void print1(unsigned int n)
{
	if (n > 9)
	{
		print1(n / 10);
	}
	printf("%d ", n % 10);
}
void print2(unsigned int n)//1234
{
	if (n < 10)
		printf("%d ", n);
	else
	{
		print2(n / 10);//123
		printf("%d ", n%10);
	}
}
int main()
{
	unsigned int num = 1234;
	print1(num);
	printf("\n");
	print2(num);
	return 0;
}

Drawing analysis : 

Writing functions does not allow the creation of temporary variables , Find the length of the string . 

Code example : 

#include <stdio.h>
int my_strlen(const char* str)
{
	if (*str == '\0')
		return 0;
	else
		return 1 + my_strlen(str + 1);
}
int main()
{
	char* p = "abcdef";
	int len = my_strlen(p);
	printf("%d\n", len);
	return 0;
}

Drawing analysis : 

3. Recursion and iteration  

practice

seek n The factorial .( Don't think about spillovers )

Code example : 

#include <stdio.h>
int Fac(int n)
{
	if (n <= 1)
		return 1;
	else
		return n * Fac(n - 1);
}

int main()
{
	int n = 0;
	printf(" Please enter an integer :>");
	scanf("%d", &n);
	int ret = Fac(n);
	printf("%d The factorial is %d\n", n, ret);
	return 0;
}

Please n Fibonacci Numbers .( Don't think about spillovers )

Code example : 

#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;
	printf(" Please enter an integer :>");
	scanf("%d", &n);
	int ret = Fib(n);
	printf(" The first %d The Fibonacci number is %d\n", n, ret);
	return 0;
}

  But we found something wrong :1. 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 ;2. Use Fac Function finding 10000 The factorial ( Regardless of the correctness of the results ), The program will crash . 

  Why is this so ? because Fib In fact, many calculations are repeated during the call of a function , The efficiency will be particularly low .

Calculate the number of operations of the third Fibonacci number

Code example :

#include <stdio.h>
int count = 0;
int Fib(int n)
{
	if (n == 3)
		count++;
	if (n <= 2)
		return 1;
	else
		return Fib(n - 1) + Fib(n - 2);
}

int main()
{
	int n = 0;
	printf(" Please enter an integer :>");
	scanf("%d", &n);
	int ret = Fib(n);
	printf(" The first %d The Fibonacci number is %d\n", n, ret);
	printf("count = %d\n", count);
	return 0;
}

Output results :

  We can see , The program has calculated the third Fibonacci number as high as 39 million times , Too inefficient .

  How to solve the above problems :

1. Rewrite recursion to non recursion .
2. 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 can be adjusted for each

Accessed by layer .

  that , The following code adopts a non recursive way to realize :

Code example : 

#include <stdio.h>
int Fac(int n)
{
	int ret = 1;
	while (n)
	{
		ret *= n;
		n--;
	}
	return ret;
}

int main()
{
	int n = 0;
	printf(" Please enter an integer :>");
	scanf("%d", &n);
	int ret = Fac(n);
	printf("%d The factorial is %d\n", n, ret);
	
	return 0;
}
#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--;
	}
	return c;
}

int main()
{
	int n = 0;
	printf(" Please enter an integer :>");
	scanf("%d", &n);
	int ret = Fib(n);
	printf(" The first %d The Fibonacci number is %d\n", n, ret);
	return 0;
}

reminder : 

1. Many problems are explained recursively , This is only because it is clearer than the non recursive form .
2. However, the iterative implementation of these problems is often more efficient than recursive implementation , Although the code is slightly less readable .
3. When a problem is quite complex , When it is difficult to implement iteratively , At this point, the simplicity of recursive implementation can compensate for the       Runtime overhead .

Conclusion  

  Every good person has a period of silence , It was a time when I made a lot of efforts but failed to get results , We call it rooting .

原网站

版权声明
本文为[A Liang joy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/207/202207260504511238.html