Elementary C language-functions

1. What is a function

We often see the concept of function in mathematics. But what are the functions in C language? Definition of function in Wikipedia: subroutine

  • In computer science, a subroutine (English: Subroutine, procedure, function, routine, method, subprogram, callable unit) is a part of a large program composed of one or more statement blocks. It is responsible for completing a specific task and is relatively independent compared to 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.

Classification of functions in C language:

  1. Library Functions
  2. Custom function

2. Library functions

Why are there library functions?

  1. High development efficiency;
  2. Good stability.

Here we have a simple look: www.cplusplus.com A
Insert picture description here
brief summary, the library functions commonly used in C language are:

  • IO function
  • String manipulation functions
  • Character manipulation function
  • Memory operation function
  • Time/date functions
  • Mathematical function
  • Other library functions
    can refer to this blog to learn about library functions
    03-C language advanced-character functions and string functions
    Note: To
    use library functions, you must include #include corresponding header files.

3. Custom function

Like library functions, custom functions have function names, 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.
The composition of the function:

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




Give a chestnut:

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

#include <stdio.h>

int get_max(int x, int y)
{
    
    
	return x > y ? x : y;
}

int main()
{
    
    
	int num1 = 2;
	int num2 = 8;
	int max = get_max(num1, num2);
	printf("max = %d\n", max);
	return 0;
}

result:
Insert picture description here

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

#include <stdio.h>
void Swap1(int x, int y)
{
    
    
	int tmp = 0;
	tmp = x;
	x = y;
	y = tmp;
}
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;
}

Insert picture description here
We will find that the same result is achieved by the exchange of even numbers. What is the reason? Let's look down

4. Function parameters

To know the reason, we first know the actual parameters (actual parameters) of the following two concepts
:

The parameters actually passed to the function, Called actual parameters. The actual parameters can be: constants, variables, expressions, functions, etc. No matter what type of variable the actual parameter is, when the function is called, they are allMust have a certain value, In order to pass these values ​​to the formal parameters.

Formal parameters (formal parameters):

The formal parameter refers toVariables in parentheses after the function name, Because the formal parameters are instantiated (allocated memory units) only during the process of the function being called, so they are called formal parameters. The formal parameters are automatically destroyed when the function call is completed. thereforeFormal parameters are only valid in functions

The parameters x, y, px, and py in the above Swap1 and Swap2 functions are all formal parameters . In the main function, the num1 and num2 passed to Swap1 and the &num1 and &num2 passed to the Swap2 function are the actual parameters .
Here we analyze the actual parameters and formal parameters of the function:
Insert picture description here
the memory allocation corresponding to the code is as follows.
Insert picture description here
Here you can see that when the Swap1 function is called, x and y have their own space, and they have exactly the same content as the actual parameters. So we can simply think: the instantiation of the formal parameter is actually equivalent to a temporary copy of the actual parameter.
The pointers px and py in Swap2 store the addresses of num1 and num2, and they point to the contents of num1 and num2 when dereferenced. Therefore, after the swap operation is performed, the contents of num1 and num2 are changed. For details of pointers, please refer to this blog
C language elementary-pointers

5. 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.

The call by value corresponds to Swap1. Because it is a call by value, only the values ​​1 and 2 of num1 and num2 are passed to the formal parameters x, y , so the values ​​of num1 and num2 will not be changed after the function is executed.
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 allows the function to establish a real connection with the variables outside the function, that is, the variables outside the function can be directly manipulated inside the function.

The call by address corresponds to Swap2, and the addresses of num1 and num2 are passed to the pointers px and py . Therefore, modifying the contents of the addresses pointed to by the pointers will change the original values ​​corresponding to num1 and num2.

6. Nested function calls and chained access

Nested call Calling a
function again in a function is a nested call

#include<stdio.h>

void FirstFun()
{
    
    
	printf("hello world\n");
}

void SecondFun()
{
    
    
	for (int i = 0; i < 3; ++i)
	{
    
    
		FirstFun();
	}
}

int main()
{
    
    
	SecondFun();
	return 0;
}

The result
Insert picture description here
chain call
takes the return value of one function as the parameter of another function.

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char arr[20] = "hello";
	int ret = strlen(strcat(arr, "bit"));
	printf("%d\n", ret);
	return 0;
}

result
Insert picture description here

7. Function declaration and definition

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 is irrelevant.
  2. The declaration of a function generally appears before the use of the function. To be satisfied, declare before use.
  3. The declaration of the function should generally be placed in the header file.

Function definition:
The definition of a function refers to the concrete realization of the function, explaining the function realization of the function.
The contents of test.h place the declaration of the function

#ifndef __TEST_H__
#define __TEST_H__
//函数的声明
int Add(int x, int y);
#endif __TEST_H__

Implementation of the content placement function of test.c

#include "test.h"
//函数Add的实现
int Add(int x, int y)
{
    
    
    return x+y;
}

This kind of multi-file writing form can be seen in the application examples of these two blogs.
C language mini game 1-Sanziqi
C language mini game 2-Minesweeper

8. Function recursion

What is recursion?
The programming technique of a program calling itself is called recursion. Recursion as an algorithm is widely used in programming languages. A process or function has a method of directly or indirectly calling 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 recursive strategy only A small amount of programs can describe the repeated calculations required in the process of solving the problem, which greatly reduces the amount of code of the program. The main way of thinking about recursion is to make big things smaller .

Two necessary conditions for recursion

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

The most classic example is to find the factorial of n

int factorial(int n)
{
    
    
    if(n <= 1)
        return 1;
    else
        return n* factorial(n-1);
}

Guess you like

Origin blog.csdn.net/qq_40076022/article/details/112717844