Functions in C language

1. What is the function?

  • In computer science, a subroutine is a part of code in a large program, which is composed of one or more statement blocks. It is responsible for completing a specific task and has relative independence compared with other codes.
  • Generally, there are input parameters and return values, which provide encapsulation of the process and hiding of details. These codes are usually integrated into software libraries.

2. C lassification of functions in C language

2.1 library functions

To sum up, the library functions commonly used in C language are:
  • IO function (input / output function)
  • String operation function
  • Character manipulation function
  • Memory operation function
  • Time / date function
  • Mathematical function
  • Other library functions

For example, C language standard can specify the standard of library function:

           int strlen(const char* str);

Function: find the length of the string pointed to by str

#include <stdio.h>
#include <string.h>
int main()
{
	char arr1[] = "abcedf";
	char arr2[] = { 0 };
	//It can copy abcdef in arr to arr2
	strcpy(arr2, arr1);

	printf("%s\n", arr2);
	return 0;
}
#include <stdio.h>
#include <string.h>
int main()
{
	char arr[] = "hello China";
	memset(arr, 'X', 5);//Changing arr + can change the modified position
	//1. The memory is set in bytes
	//2. The content of each byte is the same value
	printf("%s\n", arr);//XXXXX China
	return 0;
}

2.2 user defined functions

Function composition:
ret_type fun_name(para1, * )
{
 statement;//Statement item
}
ret_type Return type
fun_name Function name
para1    Function parameters
//Write a function to find the maximum value of two integers
#include <stdio.h>
int get_max(int x, int y)
{
	/*if (x > y)
		return x;
	else
		return y;*/
	return x > y ? x : y;
}
int main()
{
	int a = 0;
	int b = 0;
	scanf("%d%d", &a, &b);
	//Use the function to find the larger values of a and b
	//Max();
	int m=get_max(a,b);
	printf("%d", m);

	return 0;
}
//Writing a function can exchange the contents of two integer variables
#include <stdio.h>
//Formal parameter
void swap(int x, int y)
{
	int tmp = 0;
	tmp =x;
	x = y;
	y = tmp;

}
int main()
{
	int a = 0;
	int b = 0;
	scanf("%d %d", &a, &b);

	printf("Before exchange: a=%d,b=%d\n", a, b);
	//Argument
	swap(a, b);
	printf("After exchange: a=%d,b=%d\n", a, b);

	return 0;
}
//The result is that there is no change in the values of a and B

Reason for the error: when the argument is passed to the formal parameter, the formal parameter is a temporary copy of the argument, and the modification of the formal parameter will not affect the argument

//Use the pointer to change the value of a
#include <stdio.h>
int main()
{
	int a = 10;
	int* pa = &a;

	*pa = 20;
	printf("%d\n", a);

	return 0;

}
#include <stdio.h>
//Formal parameter
//void swap1(int x, int y)
//{
//	int tmp = 0;
//	tmp =x;
//	x = y;
//	y = tmp;
//
//}
void swap2(int* pa, int* pb)
{
	int tmp = *pa;
	*pa = *pb;
	*pb = tmp;
}
int main()
{
	int a = 0;
	int b = 0;
	scanf("%d %d", &a, &b);

	printf("Before exchange: a=%d,b=%d\n", a, b);
	//Argument
	//swap1(a, b);
	swap2(&a, &b);
	printf("After exchange: a=%d,b=%d\n", a, b);

	return 0;
}

3. Parameters of function

3.1 actual parameters (actual parameters)

  • The parameters actually passed to the function are called arguments.
  • Arguments can be constants, variables, expressions, functions, etc.
  • No matter what type of arguments are, they must have definite values when making a function call in order to pass these values to the formal parameters.

3.2 formal parameters (formal parameters)

    Formal parameters refer to the variables in parentheses after the function name. They are called formal parameters because they are instantiated (memory units are allocated) only when the function is called. Formal parameters are automatically destroyed after the function call is completed. Therefore, formal parameters are only valid in functions.

4. Function call

4.1 value transfer call

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

4.2 address calling

  • Addressing call is a way to call a function by passing the memory address of the variable created outside the function to the function parameters.
  • This parameter transfer method can establish a real relationship between the function and the variables outside the function, that is, the variables outside the function can be directly operated inside the function.

4.3 procedure example 5 Nested calls and chained access to functions

1. Write a function to judge whether a number is a prime number

// Write a function to judge whether a number is a prime number
//is_prime(i)
//Return 1 is a prime
//Returning 0 means it is not a prime number

#include <stdio.h>
#include <math.h>
int is_prime(int n)
{
	//Test with 2~n-1
	//Test with 2~sqrt(n)
	int j = 0;
	for (j = 2; j <= sqrt(n); j++)
	{
		if (n % j == 0)
		{
			return 0;
		}
	}
	return 1;
}
int main()
{
	//Print prime numbers between 100 and 200
	int i = 0;
	for (i = 100; i <= 200; i++)
	{
		//Judge whether i is prime
		if (is_prime(i) == 1)
		{
			printf("%d ", i);
		}
	}
	return 0;
}

2. Write a function to judge whether a year is a leap year

//Write a function to judge whether a year is a leap year
#include <stdio.h>
int is_leap_year(int y)
{
	/*if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
		return 1;
	else
		return 0;*/
	return ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0);
}
int main()
{
	//Leap years from 1000 to 2000
	int y = 0;
	for (y = 1000; y <= 2000; y++)
	{
		//Judge whether y is a leap year
		if (is_leap_year(y) == 1)
		{
			printf("%d ", y);
		}
	}
	return 0;
}

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

// Write a function to realize the binary search of an integer ordered array
//Return subscript when found
//Return - 1 if not found
#include <stdio.h>
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)
		{
			left = mid + 1;
		}
		else if (arr[mid] > k)
		{
			right = mid - 1;
		}
		else
		{
			return mid;
		}
	}
	return -1;//can't find
}
int main()
{
	//When an array passes parameters, it does not pass the entire array
	//It's the address of the first element passed
	int arr[] = { 1,2,3,4,5,6,7,8,9 };
	int k = 0;
	scanf("%d", &k);//Element to find
	int sz = sizeof(arr) / sizeof(arr[0]);
	int ret=binary_search(arr, k, sz);
	if (-1 == ret)
		printf("can't find\n");
	else
		printf("Yes, the subscript is:%d\n",ret);
	return 0;
}

4. Write a function. Every time this function is called, the value of num will be increased by 1

//Write a function. Every time you call this function, you will increase the value of num by 1
#include <stdio.h>
void test(int* p)
{
	*p = *p + 1;
	//(*p)++;
}
int main()
{
	int num = 0;
	test(&num);
	printf("%d\n", num);
	test(&num);
	printf("%d\n", num);
	test(&num);
	printf("%d\n", num);
	test(&num);
	printf("%d\n", num);
	return 0;
}

5. Nested call and chained access of functions

Functions and functions can be combined according to actual needs, that is, they call each other.

5.1 nested calls

#include <stdio.h>
void new_line()
{
 printf("hehe\n");
}
void three_line()
{
    int i = 0;
 for(i=0; i<3; i++)
   {
        new_line();
   }
}
int main()
{
 three_line();
 return 0; }
Functions can be called nested, but cannot be defined nested.

5.2 chain access

Take the return value of one function as an argument to another function.
#include <stdio.h>
#include <string.h>
int main()
{
    char arr[20] = "hello";
 int ret = strlen(strcat(arr,"bit"));//Here is an introduction to the strlen function
 printf("%d\n", ret);
 return 0; }
#include <stdio.h>
int main()
{
    printf("%d", printf("%d", printf("%d", 43)));
    return 0;
 }
//Print: 4321

Keywords: C

Added by joeiscoolone on Thu, 20 Jan 2022 03:30:02 +0200