[C language] function

Posted by bgomillion on Fri, 28 Jan 2022 16:30:56 +0100

catalogue

What is a function?

Library function

Custom function

Parameters of function

Function call

Nested call and chained access of functions

Declaration and definition of functions

Function recursion

What is a function?

Wikipedia definition of function: subroutine

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 will be input parameters and return values, which provide information about the process Encapsulation and hiding of details. These codes are often referred to as software libraries.

Classification of functions: library functions, custom functions

Library function

Library functions are learned mainly by consulting documents to understand the meaning and how to use library functions

Here we recommend a website for checking library functions: http://www.cplusplus.com

Log in to the website and try to learn the following two common library functions!

1. strcpy usage:

char * strcpy ( char * destination , const char * source );
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]="Sample string";
  char str2[40];
  char str3[40];
  strcpy (str2,str1);
  strcpy (str3,"copy successful");
  printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
  return 0;
}

2.memset usage (memory setting function)

void * memset ( void * ptr, int value, size_t num ); 

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "almost every programmer should know memset!";
  memset (str,'-',6);
  puts (str);
  return 0;
}

Note: the header file corresponding to #include must be included when using library functions

Custom function

Like library functions, custom functions have function names, return value types, and function parameters. But the difference is that these are settable
Composition form of function:
ret_type fun_name(para1, * )
{
 statement;//Statement item
}
ret_type Return type of function
fun_name Function name
para1    Function parameters
{}And its content function body

For example, writing a function can find the maximum value of two integers:

#include <stdio.h>

int get_max(int x, int y)
{
    int z = 0;
    if (x > y)
        z = x;
    else 
        z = y;
    return z; //Return maximum (return z)
}


int main()
{
    int a = 10;
    int b = 20;
    //Function call
    int max = get_max(a,b);
    
    printf("max = %d\n",max);
} 

Write a function to exchange the contents of two integers:

#include <stdio.h>

//The return type of the function is void, which means that the function does not return any value and does not need to return
//Function definition part
void Swap(int* pa,int* pb)   //pa and pb are formal parameters - formal parameters
{
    int z = 0;
    z = *pa;
    *pa = *pb;
    *pb = z;
}   //Pass address through pointer


int main()
{
    int a = 10;
    int b = 20;
    //Write a function - swap the values of two integer variables

//Function call part
    printf("Before exchange: a=%d b=%d",a,b);
    Swap2(&a,&b);           //&a. & B is the actual parameter - actual parameter
    printf("After exchange: a=%d b=%d",a,b);

    return 0;
}

From the difference between the above two examples, we can find the difference between passing values and passing addresses: after the Swap function passes parameters, we hope to exchange a and b outside the function inside the function (the external x and y will be exchanged in this process). In this way, the relationship between the inside and outside of the function will be established. Only when the address is passed, the inside of the function can be found through the address.

Parameters of function

Formal parameters and arguments: according to the comments in the above example, the parameters passed by the function when calling the function are called arguments, and the x and y written in the function definition are called formal parameters.

Actual parameter (actual parameter):

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.

Formal parameter (formal parameter):
Formal parameters refer to the variables in parentheses after the function name, because formal parameters are instantiated (within the assignment) only during the process of function call

Storage unit), so it is called formal parameter. Formal parameters are automatically destroyed after the function call is completed. Therefore, formal parameters are only valid in functions.

After the formal parameter is instantiated, it is actually equivalent to a temporary copy of the argument.

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

Nested call and chained access of functions

  1. Nested Call
Functions and functions can be combined according to actual needs, that is, they call each other. Functions can be called nested, but cannot be defined nested . , for example:
#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;
}

Note here: the previous function can call the following function, that is, new_ The three defined later can be called in the line function_ Line function

      2. Chain access

Chained access refers to taking the return value of one function as the parameter of another function, which is used as follows:
//Normal call
int len = strlen("abc");
printf("%d\n",len);

//Chain access
printf("%d\n",strlen("abc"));

//The printing results of the above two cases are the same

Declaration and definition of functions

  1. 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 depends on the function declaration.
     2. The declaration of a function usually appears before the use of the function. To meet Declaration before use .                                         3. The declaration of a function is usually placed in the header file
  2. Function definition: the definition of a function refers to the specific implementation of the function and explains the function implementation of the function.

In the vs compiler, you will find that there are c and h is a file with extended name. The difference between them is: test h declaration of placement function, test Implementation of c placement function. The specific syntax is as follows:

//Declaration of function
int Add(int x, int y);

//Implementation of Add function
#include "test.h"

int Add(int x, int y) 
{
     return x+y; 
}

Function recursion

What is recursion?
The programming skill of program calling itself is called recursion( recursion ).
As an algorithm, recursion is widely used in programming languages. A process or function has a method to call itself directly or indirectly in its definition or description. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem. The recursive strategy can describe the multiple repeated calculations required in the problem-solving process with only a small number of programs, which greatly reduces the amount of code of the program. The main way of thinking about recursion is to make big things small
Problems with recursion:
The stack space allocated by the system to the program is limited, but if there is an dead loop or (dead recursion), it may lead to the continuous development of stack space and eventually the depletion of stack space. This phenomenon is called stack overflow; It is inefficient, so we should try our best to find non recursive methods to solve the problem

Let's take the solution of Fibonacci sequence as an example. Finally, we output count, which is a very large value. That is to say, we have made many calculations in the solution process, but these calculations are actually a lot of repetitions, which is not as efficient as using iteration

int count = 0;//global variable
int fib(int n) 
{
     if(n == 3)
     count++;

     if (n <= 2)         
         return 1;
     else
        return fib(n - 1) + fib(n - 2);
}

Topics: C