Detailed notes on the most complete C language functions in history

Posted by moleculo on Fri, 04 Mar 2022 07:55:36 +0100

function

catalogue

  1. What is a function
  2. Library function
  3. Custom function
  4. Function parameters
  5. function call
  6. Nested call and chained access of functions
  7. Declaration and definition of functions
  8. Function recursion

1. What is the function

Function f(x)=2*x+1 in Mathematics

But what are the functions in C language? Defined in Wikipedia as a subroutine.

In computer science, a subroutine is a part of code in a large program, which is composed of one or more statement blocks
Yes. 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
Parts library.

Classification of functions in C language

1. Library function

2. User defined function

2. Library function

What are library functions?

Library function is a way to encapsulate and store functions for users. The method is to compile some commonly used functions and put them in a file for different people to call. When calling, just add the file name where it is located with #include < >.

Why are there library functions?

1. We know that when we learn C language programming, we are always eager to know the result after a code is written, and want to print the result on our screen. At this time, we will frequently use a function: print information to the screen according to a certain format (printf).

2. In the process of programming, we will frequently copy some strings (strcpy).

3. In the process of programming, we will frequently do some string comparison (strcmp)

In order to support portability and improve code efficiency, a series of similar library functions are provided in the basic library of C language.

The library functions commonly used in C language are:
IO function
String operation function
Character manipulation function
Memory operation function
Time / date function
Mathematical function
Other library functions

To put it simply, two library functions

1.strcpy

Using MSDN, we can refer to the description and explanation of the library function. You need to know some English here. MSDN says Copy a string, which means to Copy a string. This function requires two parameters, the first is the destination and the second is the source, which means to copy the source string to the destination. Look at the following code and output:

//strcpy string copy function
#include<string. h> / / header file
int main()
{
	char arr1[20] = { 0 };
	char arr2[] = "hello world";
	strcpy(arr1, arr2);
	printf("%s", arr1);//Print arr1 this string% s - print as string
	return 0;
}

2.memset

The explanation of this function is to set the buffer to the specified character and set all the contents of a block of memory to the specified value. This function requires three parameters, void *memset(void *s, int ch, size_t n). Replace the N bytes after the current position in s with CH and return s. Look at the following code and output:

//memset - memory setting
#include<string. h> / / header file
int main()
{
	char arr[] = "hello world";
	memset(arr, 'x', 5);
	printf("%s\n", arr);
	return 0;
}

How do we learn to use library functions?
We should learn how to use query tools:
MSDN(Microsoft Developer Network)

www.cplusplus.com

http://en.cppreference.com

The third learning website, if you want to see Chinese, replace the front en with zh.

3. User defined function

Like library functions, custom functions have function names, return types and function parameters. The difference is that the custom function is designed by ourselves, which has a lot of room to play.

Write a function to find the larger value of two numbers

//Function implementation
int get_max(int x,int y)
{//Return type / / function name / / parameter type passed in
    return x>y?x:y;//Returns a larger value
}
int main()
{
    int a=10;
    int b=20;
    //Function call
    int max=get_max(a,b);//Put the larger value returned into max
   	printf("%d\n",max);
    return 0;
}

Write a function to exchange the values of two variables

//Write void where the function returns the type, indicating that the function does not return any value and does not need to return
void Swap1(int x,int y)
{
    int temp=0;
    temp=x;
    x=y;
    y=temp;
}
int main()
{
    int a=10;
    int b=20;
    //Write a function to exchange the values of two integer variables
    printf("Before exchange: a=%d b=%d",a,b);
    Swap1(a,b);
    printf("After exchange: a=%d b=%d",a,b);
    return 0;
}

However, the exchange failed. Why didn't this function complete the task?

In practice, when a and b transfer functions, they create a new space x and Y. here, they only exchange the values of x and Y without the right to operate a and b. A and b are independent spaces with x and Y. * * the values monitored during debugging in the figure below** You can see that the addresses of a and x are different, and the addresses of b and y are different.

So how can we complete the exchange?

int main()
{
    int a=10;//4 bytes of space
    int *pa=&a;//pa is a pointer variable
    *pa=20;
    printf("%d",a);//20
    return 0;
}

In the above code, we can find a through * pa and change the value of a to 20. Then our exchange function can be written as follows:

#include<stdio.h>
void Swap2(int* pa,int* pb)
{
    int temp=0;
    temp=*pa;//*pa is to find a through pa
    *pa=*pb;
    *pb=temp;
}
int main()
{
    int a=10;
    int b=20;
    //Write a function to exchange the values of two integer variables
    printf("Before exchange: a=%d b=%d",a,b);
    Swap2(&a,&b);
    printf("After exchange: a=%d b=%d",a,b);
    return 0;
}

If we pass in the addresses of a and b, then the operations in the function are a and b.

You can see that the address is transferred in at this time. The address of pa is the same as that of a, and the address of pb is the same as that of b

4. Parameters of function

Function call:

Function definition:

a and b in Swap1 and Swap2 function calls are actual parameters, and x, y, pa and pb in Swap1 and Swap2 function definitions are formal parameters.

Actual parameters

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

Example:

 	int a=10;
    int b=20;
    int max=get_max(a,get_max(3,5));//Put the larger value returned into max

get_max(3,5) gets 5, then int max=get_max(a,5).

Formal parameters

Formal parameters refer to the variables in parentheses after the function name, because formal parameters are instantiated (allocated) only when the function is called
Memory unit), so it is called formal parameter. Formal parameters are automatically destroyed after the function call is completed. Therefore, the formal parameters are only
Valid in function. After the formal parameter is instantiated, it is equivalent to a temporary copy of the argument.

5. Function call

Value passing 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. The following figure shows the value transfer call:

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 true relationship between the function and the variables outside the function, that is, the function can be operated directly inside
As an external variable of a function. The following figure shows the address call:

practice

Write a function to judge prime numbers

#include<stdio.h>
int is_prime(int n)
{
    int j=0;
    for(j=2;j<n;j++)
    {
        if(n%j==0)
        {
            return 0;
        }
    }
    return 1;
}
int main()
{
    //Prime 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;
}

Write a function to judge leap years

#include<stdio.h>
//is_leap_year
//If it is a leap year, return 1
//Return 0 if it is not a leap year
int is_leap_year(n)
{
    //return ((y%4==0&&y%100!=0)||(y%400==0))
   if((n%4==0&&n%100!=0)||(n%400==0))
   {
       return 1;
   }
    return 0;
}
int main()
{

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

Write a function to realize binary ordered search

#include<stdio.h>
//int binary_search(int *a,int k,int s)
int binary_search(int a[],int k,int s)
{
    int left=0;
    int right=s-1;
    while(left<=right)
    {
    	int mid=(left+right)/2;
        if(a[mid]>k)
        {
            right=mid-1;
        }
        else if(a[mid]<k)
        {
            left=mid+1;
        }
        else
        {
        	return mid;
        }
    }
    return -1;//Can not find
}
int main()
{
    int arr[]={1,2,3,4,5,6,7,8,9,10};
    int key=7;
    int sz=sizeof(arr)/sizeof(arr[0]);
    //Return to the location when you find it
    //Cannot find return - 1
    //Array arr parameters are not actually passed to the array itself
    //Only the address of the first element of the array was passed
   	int ret = binary_search(arr,key,sz);
    if(-1==ret)
    {
        printf("can't find\n");
    }
    else
    {
        printf("Yes, the subscript is:%d\n",ret);
    }
    return 0;
}

Array arr parameters are not actually passed to the array itself
Only the address of the first element of the array was passed

Note: the number of elements of the array cannot be calculated in the function when the array parameter is passed.

Write a function. Every time you call this function, you will increase the value of num by 1

#include<stdio.h>
void Add(int *p)
{
    (*p)++;
}
int main()
{
    int num = 0;
    //Every time this function is called, the value of num is increased by 1
    Add(&num);
    printf("%d\n",num);//1
    
    Add(&num);
    printf("%d\n",num);//2
    
   	Add(&num);
    printf("%d\n",num);//3
    return 0;
}

6. Nested call and chained access of functions

Nested Call

int test3()
{
    printf("haha\n");
}
int test2()
{
    test3();//Call test3
}
int main()
{
    test2();
    return 0;
}

Chain access

Take the return value of one function as the parameter of another function.

#include<stdio.h>
#include<string.h>
int main()
{
    int len = strlen("abc");
    printf("%d\n",len);
    //Chain access
    printf("%d\n",strlen("abc"));
    return 0;
}

The code printing is shown in the figure below:

int main()
{
    printf("%d",printf("%d",printf("%d",43)));//Print 4321
}

Print as follows:

The value returned by the printf function is the number of characters. Let's explain the code. The first printf prints the return value of printf ('% d', printf ('% d', 43)), the second printf prints the return value of printf ('% d', 43)), and the third printf prints 43. The first print43, 43 are the number of two characters, so the second printf prints 2 and 2 are one character, So the first printf prints 1.

7. Declaration and definition of functions

Function declaration

  1. Tell the compiler what a function is called, what the parameters are and what the return type is. But whether it exists or not has nothing to do with it
    It's important.
  2. The declaration of a function usually appears before the use of the function. To meet the requirements of declaration before use.
  3. The declaration of the function is usually placed in the header file.
int main()
{
    int a=10;
    int b=20;
    
    int c=Add(a,b);
    printf("%d\n",c);
    
    return 0;
}
int Add(int x,int y)
{
    return x+y;
}

A warning will appear, as shown in the following figure:

The compiler scans from front to back. When it sees Add, the compiler will warn if it has not seen Add. At this time, it needs to declare it

int main()
{
    int a=10;
    int b=20;
    //Function declaration - inform
    int Add(int,int);
    int c=Add(a,b);
    printf("%d\n",c);
    
    return 0;
}
int Add(int x,int y)
{
    return x+y;
}

There will be no alarm at this time.

Definition of function

The definition of function refers to the specific implementation of the function and explains the function implementation of the function.

We usually test Declaration of function placed in H

In test Implementation of placement function in C

8. Function recursion

What is recursion?

The function itself is recursive. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem to solve. The idea of recursion only needs a small number of programs

int main()
{
    printf("haha\n");
    main();
    return 0;
}

The main function calls itself

The program will loop, call itself, and finally overflow the stack. We will explain the stack overflow below

Exercise 1

Accept an integer value and print each bit of it in order. For example: input 1234, output 1234

1234%10 = 4

1234/10=123 123%10 = 3

123/10=12 12%10 = 2

12/10=1 1%10 = 1

1/10=0

%10 is a single digit

What about recursion?

Make big things small

print(1234)

print(1234) can be split into: print(123) 4

print(123) can be split into: print(12) 3 4

print(12) can be split into: print(1) 2 3 4

void print(unsigned int n)
{
    if(n>9)
    {
        print(n/10);//Remove 1234 into 123
    }
    printf("%d ",n%10);
}
int main()
{
    unsigned int num = 0;
    scanf("%d",&num);//1234
    //Recursion - call yourself
    print();//Each bit of the parameter print of the function can be printed
    return 0;
}

Two necessary conditions of recursion

1. There is a constraint. When this constraint is met, recursion will not continue.
2. Get closer to this limit after each recursive call

However, meeting these two conditions is not necessarily correct.

void test(int n)
{
    if(n<10000)
    {
        test(n+1);
    }
}
int main()
{
    test(1);
    return 0;
}

At this time, the program will collapse and the stack overflows, as shown in the exception below

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-fdckvqfp-1618739053573) (C: \ users \ 15191107746 \ appdata \ roaming \ typora \ typora user images \ image-20210418100021065. PNG)]

Explanation of recursive stack overflow:

The memory allocation space is shown in the figure below:

Let's look at the stack area separately:

In fact, the parameters of the function call are passed through the stack space. For recursive calls, the function can exit in turn only after reaching the last end point. Before reaching the last end point, the occupied stack space has not been released. If the number of recursive calls is too many, the occupied stack resources may exceed the maximum value of the thread, resulting in stack overflow, Causes the program to exit abnormally.

When writing recursive code, you should pay attention to:

1. Dead recursion is not allowed. There are jump out conditions. Each time recursion approaches the jump out conditions

2. The recursion level cannot be too deep

Recommend a website

www.stackoverflow.com

Equivalent to the programmer's knowledge!

Exercise 2

Writing a function is not allowed to create a temporary variable. Find the length of the string

#include<stdio.h>
#include<string.h>
int main()
{
    char arr[]="abc";
    //['a']['b']['c']['\0']
    printf("%d\n",strlen(arr));
    return 0;
}

Simulate the implementation of a strlen function

#include<stdio.h>
#include<string.h>
int my_strlen(char* str)
{
    int count = 0;
    while(*str != '\0')
    {
        count++;
        str++;
    }
    return count;
}
int main()
{
    char arr[]="abc";
    //['a']['b']['c']['\0']''
    printf("%d\n",my_strlen(arr));//The address of the character 'a' is passed
    return 0;
}

Although it seems that this topic has been completed, it does not meet the requirements of the topic. The topic is not allowed to create temporary variables

We need to use the idea of recursion to solve it

my_strlen("abc");

1+my_strlen("bc");

1+1+my_strlen("c");

1+1+1+my_strlen("\0")

1+1+1+0=3

It is also the idea of making big things small

#include<stdio.h>
#include<string.h>
int my_strlen(char* str)//str points to 'a'
{
	if(*str!='\0')
        return 1+my_strlen(str+1);
    else
        return 0;
}
int main()
{
    char arr[]="abc";
    //['a']['b']['c']['\0']''
    printf("%d\n",my_strlen(arr));//The address of the character 'a' is passed
    return 0;
}

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kmlh696l-1618739053575) (C: \ users \ 15191107746 \ appdata \ roaming \ typora user images \ image-20210418123754220. PNG)]

At the beginning of entering the function, str points to 'a', 'a' is not equal to \ 0, return 1+my_strlen(str+1), recursive call. str+1 points to 'b', b is not equal to \ 0. Continue the recursive call. str+1 points to 'c', c is not equal to \ 0. Continue the recursive call. At this time, str+1 points to \ 0,return 0, and there will be no more calls. At this time, the return link is reached, and the return is the place where it is called, so return 1, return2, return 3, and finally return to the main function.

Recursion and iteration

Exercise: Factoring n (regardless of overflow)

n!

1*2*3*...*n

int main()
{
    int n=0;
    scanf("%d",&n);
    int i=0;
    int ret=1;
    //iteration
    for(i=1;i<=n;i++)
    {
        ret=ret*i;
    }
    printf("%d\n",ret);
    return 0;
}

Mathematically defined, as shown in the figure

So we can write code like this

int Fac(int n)
{
    if(n<=1)
        return 1;
    else
        return n*Fac(n-1);
}
int main()
{
    int n=0;
    scanf("%d",&n);
    int ret=Fac(n);
    printf("%d\n",ret);
    return 0;
}

Some functions can be solved iteratively or recursively

practice:

Find the nth Fibonacci number?

int count = 0;
int Fib(int n)
{
    if (n == 3)//Count the number of calculations of the third Fibonacci number
        count++;
    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);
    printf("count:%d\n", count);

    return 0;
}

if (n == 3)//Count the number of calculations of the third Fibonacci number
    count++;

It can be seen that the third Fibonacci number is calculated 39088169 times.

Too inefficient - repeat a lot of calculations!

Recursive efficiency is too low

It can be solved by circulation with high efficiency. See the following code:

int Fib(int n)
{
   	int a=1;
    int b=1;
    int c=1;
    while(n>2)//From the third Fibonacci number
    {
        c = a+b;
        a=b;
        b=c;
        n--;
    }
    return c;
}
int main()
{
    int n=0;
    scanf("%d",&n);
    int ret=Fib(n);
    printf("%d",ret);
    return 0;
}

When using recursion is inefficient, we can use non recursive methods to iterate.

There are also recursive problems:

Hanoi Tower problem

Frog jumping steps:

You can jump 1 and 2 at one time

How many mid jump methods are there in n steps

Similar to the Fibonacci sequence!

Topics: C