C learning_9 (Functions)

Table of contents

function

The concept of function

What the function does

Classification of functions

function parameters

function call


function

The concept of function

        Concept: A function in C language is a code block that encapsulates a certain function and can be called anywhere in the program.

return value type function name (argument list)

{

        function body

        return return value;

}

1. The return value type specifies the data type returned by the function

2. The function name is the name of the function

3. The parameter list contains the input parameters required by the function

4. The function body contains the specific functions implemented by the function

5. The return statement is used to pass the calculation result to the function caller.

Definition of function from Wikipedia: Subroutine 

        In computer science, a subroutine (English: Subroutine, procedure, function, routine, method, subprogram, callable unit) is a certain part of the 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 will be input parameters and a return value, providing the encapsulation of the process and the hiding of details. These codes are often integrated as software libraries.

What the function does

        Function: Encapsulating the specific functional logic in the program in a function can greatly improve the readability and maintainability of the program. In the program, the corresponding functions are realized by calling functions, which avoids the appearance of lengthy and repetitive codes and facilitates the reuse of codes.

Classification of functions

        1. Library functions

        Library functions refer to a collection of program functions that have been written, tested and optimized, and these functions can be called by other programs. Library functions are usually written to implement some common functions, such as scnaf function, printf function, strlen function , etc. Library functions help program developers improve development efficiency and code quality, and avoid reinventing the wheel. In program development, using library functions can simplify the code and improve the readability and maintainability of the code. The C language does not directly implement the library functions, but provides the standards of the C language and the conventions of the library functions.

Summary - The library functions commonly used in C language have:

IO function: input and output function scanf printf getchar putchar

String manipulation functions: strlen strcmp

Character operation function: islower isupper

Memory manipulation function: menset memcmp

Time/date functions: time

Mathematical functions: sqrt pow

Other library functions

        Next, let's learn two library functions:

(1).strcpy

But whether this function copies '\0' or not, we still need to verify it.

 

(2).memset 

2. Custom functions 

        User-defined functions refer to functions written by programmers themselves , which can be called by other programs just like library functions. Different from library functions, custom functions are written according to the needs of programmers and specific functions, and can be designed according to specific business needs, and can implement some complex algorithms or processes.

The composition of the function:

ret_type fun_name(para1, *)
{     statement;//statement item } ret_type return type fun_name function name para1    function parameter




Write a custom function to find the maximum of two integers.

function parameters

Here we first write a function to exchange two integer variables

Here we need to introduce the function parameters.

3.1 Actual parameters (actual parameters)

The parameters actually passed to the function are called actual parameters. Actual parameters can be: constants , variables , expressions , functions , etc. 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)

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.

! ! ! ! ! ! Final writing:

//写一个函数实现两个整型变量的交换
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void swap(int* x, int* y)//形式参数 - 形参
{
	int temp = 0;
	temp = *x;
	*x = *y;
	*y = temp;
}
int main()
{
	int a = 0;
	int b = 0;
	scanf("%d %d", &a, &b);
	printf("交换前:%d %d\n", a, b);
	swap(&a, &b);	//实际参数 - 实参
	printf("交换前:%d %d\n", a, b);
	return 0;
}

So when do we need to pass the address, and when do we need to pass the value? Then we need to understand the function call

function call

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.
Call by address:
        Call by address is a way to call a function by passing the memory address of the variable created outside the function to the function parameter.
This way 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.

 Summarize:

Write down and write a few codes to understand the practical application of passing address and passing value .

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

#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 = 101; i <= 200; i += 2)
	{
		//判断i是否是素数
		//由于这里只是使用这个值,并不需要修改,所以传值
		if (is_prime(i) == 1)
			printf("%d ", i);
	}
	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 year)
{
	if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
		return 1;
	return 0;
}
int main()
{
	int year = 0;
	scanf("%d", &year);
	//判断闰年
	//由于这里只是使用这个值,并不需要修改,所以传值
	if (is_leap_year(year) == 1)
		printf("%d年是闰年!", year);
	return 0;
}

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

#include<stdio.h>
int binary_search(int arr[],int sz,int k)
{
	int left = 0;
	int right = sz - 1;

    //int mid = (left + right) / 2;//容易超出int类型的范围
	int mid = left + (right - left);
	while (left<=right)
	{
		if (arr[mid] > k)
			right = mid - 1;
		else if (arr[mid] < k)
			left = mid + 1;
		else
			return mid;
	}
	return -1;
}
int main()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	int k = 5;
	//二分查找k值
	//由于这里只是使用这个值,并不需要修改,所以传值
	int ret = binary_search(arr, sz, k);
	if (ret == -1)
		printf("没找到!\n");
	else
		printf("找到了,下标是:%d\n", ret);
	return 0;
}

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

​#include<stdio.h>
void num_addtion(int* n)
{
	*n += 1;
}
int main()
{
	int num = 0;
	//每次调用函数num都会+1
	//由于这里需要修改num的值,所以传址
	num_addtion(&num);
	printf("%d\n", num);

	num_addtion(&num);
	printf("%d\n", num);

	num_addtion(&num);
	printf("%d\n", num);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_64446981/article/details/130331254
Recommended