[C Language] Describe functions in detail

Table of Contents

Preface

1. What is a function?

2. What is a library function?

2.1 Standard library and header files

3. About custom functions

3.1 Grammatical form of function

3.2 Function examples

4. Formal parameters and actual parameters

4.1 Actual parameters

4.2 Formal parameters

4.3 Relationship between actual parameters and formal parameters

5. return statement

5.1 Interlude

6. Use arrays as function parameters

7. Nested calls and chained access of functions

7.1 Nested calls

7.2 Chain access

8. Declaration and definition of functions

8.1 In a single file

8.2 In multiple files

Conclusion


Foreword

In large code projects, we cannot do without functions, which play a huge role. Today we will learn this important knowledge module together – Function

1. What is a function

The first time we heard this word was probably in mathematics class. y = kx + b is a function that knows the algebraic relationship between x and y. Similarly, there are functions in the C language, which are also called “subprograms”. We can know from the name: a function is a small piece of code that completes a specific function. It has two advantages:

  1. We can decompose the functions required for a large code project into several functions, which makes it easier for us to manage operations.
  2. If we need to use a certain function repeatedly, we can write the function as a function. The function is reusable and can improve our development efficiency.

In C language, there are two common functions: library functions and custom functions. Library functions come with the compiler and can be used directly after we define the corresponding header file, which is very convenient; custom functions refer to functions we create according to our own needs. Someone may want to ask: What is a library function and what is a header file? Hey, don’t worry, let’s explain one by one.

2. What is a library function

2.1 Standard Library and Header Files

Various syntax standards are stipulated in the C language standard, and compiler manufacturers have developed some common functions based on the syntax standards, such as our commonly used input and output scanf and printf , The library that is a collection of common functions is called the standard library. These functions are also called library functions. Here is an official library function header file URL: C Standard Library Header File – cppreference.com. When encountering standard library problems You can find it in

3. About custom functions

Custom functions are the key to our learning. Various functions in actual projects need to be developed by ourselves, which requires custom functions to achieve the functions we want.

3.1 Syntax form of function

ret_type name (formal parameter)

{

. . . (function body)

}

  • ret_type: refers to the data type of the function return value
  • name: It is the name of the function. You can choose it yourself, but try to make it meaningful.
  • Formal parameters: established to receive actual parameters
  • Function body: describes the specific process of the function completing the task

3.2 Function Instance

Example: Write an addition function to add two integers

 #include <stdio.h>

    int add(int n, int m)
    {
    int z = n + m;
    return z;
    }

    int main()
    {
    int a = 0;
    int b = 0;
    scanf("%d %d", & amp;a, & amp;b);
    //Call the addition function to add a and b
    //Define c variable to receive the added number
    int c = add(a, b);
    printf("%d\
", c);
    return 0;
    }

Let’s enter 10 and 20 and see what the result is:

Yes, as we expected, the result is 30, which is a simple addition function. In fact, we can also simplify the function body of this addition function, like this:

 int add(int n, int m)
        {
        return n + m;
        }

There are a few points to note during this process:

  1. The function name is customized, just name it according to the actual situation.
  2. The number of parameters must also be determined according to the actual situation, it can be zero or multiple
  3. Regarding the return value of the function: The function can return a value or not. It should be determined according to the actual situation. If it does not return, use void

4. Formal parameters and actual parameters

In functions, we divide function parameters into two types, actual parameters and formal parameters. We use the addition function written earlier to explain the parameters

 #include <stdio.h>

    int add(int n, int m)
    {
    int z = n + m;
    return z;
    }

    int main()
    {
    int a = 0;
    int b = 0;
    scanf("%d %d", & amp;a, & amp;b);
    //Call the addition function to add a and b
    //Define c variable to receive the added number
    int c = add(a, b);
    printf("%d\
", c);
    return 0;
    }

4.1 Actual Parameters

When we call the add function in line 16, the parameters a and b passed to the function are called actual parameters, that is, actual parameters. The actual parameters are the parameters actually passed to the function.

4.2 formal parameters

In the third line of code, n and m in parentheses after the function name add are formal parameters, referred to as formal parameters. The two of them only exist formally and do not apply for space in the memory. They do not really exist, so they are called formal parameters. Only when the function is called, the formal parameters will apply for space in memory in order to store the values passed by the actual parameters.

4.3 The relationship between actual parameters and formal parameters

Although we often say that actual parameters will pass values to formal parameters, they each have independent memory space. When passing occurs, the formal parameter is a temporary copy of the actual parameter. Our changes to the formal parameter will not affect the actual parameter.

5. return statement

  1. return can be followed by a value or an expression. If it is an expression, it will execute the expression first and then return the result of the expression.
  2. return can also be followed by nothing, just write return. At this time, the return type of the function should be void, which is the empty type.
  3. After the return statement is executed, the following code will no longer be executed and will jump out of the function directly.
  4. If there are branch statements such as if in the function, remember to write return in each case, otherwise a compilation error will occur.

Example: Print 1 ~ n numbers

 #include <stdio.h>

    void print(int m)//Only print the number and do not need to return any value, so use void
    {
    if (m < 1)//determine whether it is greater than 1
    return;//No return value
int i;
for (i = 1; i <= m; i + + )
    {
    printf("%d ", i);
    }
return;//Similarly does not return a value
    }

    int main()
    {
int n = 0;
scanf("%d", & amp;n);
print(n);
printf("\
");
return 0;
    }

When we enter 10, 1 ~ 10 is printed; when we enter a non-integer, such as – 10, it is not printed.

Note: You cannot use break to jump out of a function. It can only be used to jump out of a loop. In a function, we use return to jump out of a function.

5.1 Interlude

Let’s take a look at a simple function. Do you think it is correct to write it like this:

 #include <stdio.h>

    void print()
    {
    printf("hello world\
");
    return;
    }

    int main()
    {
    print();
    print(10);
    print(100);
    return 0;
    }

Hey, it can still print out three lines of “hello world”. Why is this? We clearly didn’t write formal parameters, so why doesn’t the compiler report an error?

Everyone also knows that writing this way is not standardized, so we can add void in the brackets after the function name to clearly tell the compiler that we do not need parameters. If we write it like this again, it will report an error.

6. Arrays are used as parameters of functions

We will inevitably encounter situations where we need to pass an array as a parameter to a function, so let us take a look at the following code

Example: Create a one-dimensional array

Implement the function init() to initialize the array to all 0s; implement print() to print each element of the array.

 #include <stdio.h>
    Set array content
    void Set(int arr[], int sz, int set)
    {
        int i = 0;
        for (i = 0; i < sz; i + + )
        {
            arr[i] = set;
        }
    }
    //Print the contents of the array
    void Print(int arr[], int sz)
    {
        int i = 0;
        for (i = 0; i < sz; i + + )
        {
            printf("%d ", arr[i]);
        }
        printf("\
");
    }

    int main() {
        int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int sz = sizeof(arr) / sizeof(arr[1]);//Determine the number of elements
        Print(arr, sz);//Print the contents of the array
        Set(arr, sz, 0);//Set the contents of the array
        Print(arr, sz);
        return 0;
    }

The Set function here requires the ability to set the array content, so the array needs to be passed to the function as a parameter, and when setting the array content, you also need to know the number of array elements in order to traverse the array. So we need to pass two parameters to the Set function: the array and the number of elements in the array; similarly, the Print function is the same. Only by knowing the array and the number of elements in the array can we print each element of the array.

Several important knowledge points about array parameter passing:

  1. The array name (arr) is written when passing parameters in an array.
  2. In a one-dimensional array, the number of elements can be omitted when writing the formal parameter (that is, the number of elements does not need to be written in the square brackets); in a two-dimensional array, rows can be omitted, but columns cannot be omitted.
  3. After the array parameters are passed, the array of formal parameters and the array of actual parameters are in the same space, and the formal parameters will not create a new array.

7. Nested calls and chained access of functions

7.1 Nested Call

The so-called nested call means calling a function within a function. We can improve development efficiency through nested calls between functions.

Example: Calculate how many days there are in a certain month of a certain year

We can split the question into two functions, one to determine whether the year is a leap year, and the other to calculate the number of days.

There are two functions is_leap_year and get_day

 #include <stdio.h>

    //Judgment of leap year, returns 1 if it is a leap year, not 0
    int is_leap_year(int y)
    {
    if (((y % 4 == 0) & amp; & amp; (y % 100 != 0)) || (y % 400 == 0))
    {
    return 1;
    }
    else
    {
    return 0;
    }
    }

    //Determine the number of days
    int get_day(int y,int m)
    {
    int days[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    //Subscript (month) 0 1 2 3 4 5 6 7 8 9 10 11 12
    int day = days[m];
    //If it is a leap year and the number of months is 2, add 1 to day
    if (is_leap_year(y) & amp; & amp; m == 2)
    {
    day + + ;
    }
    return day;
    }
    int main()
    {
    int year = 0;
    int month = 0;
    scanf("%d %d", & amp;year, & amp;month);
    int d = get_day(year, month);
    printf("%d\
", d);
    return 0;
    }

7.2 Chain Access

Chained access refers to using the return value of one function as a parameter of another function. Stringing it together like a chain is called chained access.

Example: Calculate the length of a string and print it

 #include <stdio.h>

    int main()
    {
    //strlrn calculates the length of the string and uses the return value as a parameter of the printf function
    printf("%d\
", strlen("abcdef"));
    return 0;
    }

operation result:

8. Function declaration and definition

8.1 in a single file

Let’s use the addition function as an example

There is nothing wrong with using such a function, but what happens if we swap the definition and call?

Because the C language compiler scans the code from top to bottom, if we call it first and then define it, an error will occur. Therefore, before we use the function, we still need to declare the function first. We only need to explain the function name, function return type and parameters. The definition of a function is a special function declaration, which is both a declaration and a definition.

8.2 in multiple files

When the amount of code is relatively large, we will not put all the code in the same .c file; we often split the code into multiple files, like the following:

  • add.c
 //Definition of function
    int add(int x, int y)
    {
        return x + y;
    }
  • add.h
 //Declaration of function
    int add(int x, int y);
  • test.c
 #include <stdio.h>
    #include "add.h"

    int main()
    {
        int a = 10;
        int b = 20;
        printf("%d\
", add(a, b));
        return 0;
    }

Writing code in this way has the following advantages:

  • The logic is clear. There is only the main function main in the main file test.c , and other functions are split into other files to make the code look more concise.
  • Convenient for multiple people to collaborate. Within the company, many people often need to cooperate in development, so this development method is needed.
  • Convenient code hiding. The process of realizing the specific function of the function can be hidden in a special .c file

Conclusion

Today we learned the relevant knowledge of functions together, and clearly understood library functions, custom functions, what are the actual parameters, precautions for return statements, etc. I don’t know what you think, but you are welcome to have a friendly discussion in the comment area. If you think it’s good, please give it a like, thank you very much!