C Language Discovery Tour | Part One Lesson 11: Functions

Posted May 28, 202012 min read

Author Xie Enming, the public number " Programmer Union ".
Reprint please indicate the source.
Original: https://www.jianshu.com/p/148...

"C Language Exploration Journey" full series

brief introduction


1 Introduction
2. Function creation and call
3. Examples of some functions
4. Summary
5. The first part of the exercises

1 Introduction


The last lesson was C language exploration tour | Part I Lesson 10:The first C language game .

In this lesson, we will end the first part(basic part) of "C language exploration journey" with function as the top priority, and the second part will greet us with the advanced technology of C language.

The second part will be more difficult, but don't worry, we will learn step by step. As long as the direction is right, willing to spend time, C language is not scary at all.

In this lesson, we will also tell you the principles on which C language programs are based.

We are going to learn how to manage the program in blocks, a bit like Lego bricks.

In fact, all large programs in C language are a collection of small blocks, and these small blocks are called functions. Function English is function, function means "function; \ [数 ]function".

In object-oriented languages ​​(such as Java, C ++), functions are also known as methods. Of course, here we only discuss C language(process-oriented language), not object-oriented language.

2 . Function creation and call


We have learned in the previous course:all C language programs are started by the main function. At that time we also showed a summary diagram with some terms:

The top part is called "preprocessing instruction", it is easy to identify, because it starts with # sign, and it is always placed at the front of the program.

The following part is the function we want to learn. The example here is the main function.

As mentioned before, the degree of C language is based on the main function as the entry function. To run a C program, there must be a main function. It's just that all the programs we have written so far, including the mini-games from the previous lesson, are just playing in the main function. We have not jumped out of the main function.

Then you may ask:"Is this bad?"

The answer is:This is not to say that this is bad, but this is not what C programmers usually do. Few programmers will only write code inside the braces of the main function.

The programs we have written so far are still relatively short, but imagine that if the program becomes very large, the code is tens of thousands or even millions of lines, do we still put these codes in the main function?

So we will now learn how to plan our program better. We have to learn to divide the program into many small pieces, just like every small piece of Lego bricks, these small pieces can be put together to form a lot of fun shapes.

These small pieces of programs are called functions.

A function performs certain operations and returns a value. A program is a sequence of codes that is responsible for completing specific tasks.

A function has input and output, as shown below:

We can think of the function as a machine for making sausages. At the input end, you put the pig in, and at the output end, the sausage comes out. This is sour, it goes without saying ~

Function is like a sausage maker

When we call a function in a program, three steps occur in sequence:

  1. Input:Pass in some information to the function(by giving the function some parameters).
  2. Operation:Using the information passed in the input, the function can complete a specific task.
  3. Output:After the operation is completed, the function returns a result, which is called output or return value.

For example, for example, we have a function called multipleTwo, which is used to multiply the input by two, as shown below:

The purpose of the function is to make the source code more structured and save the number of source code, because we don't have to enter repeated code fragments every time and just call the function.

Imagine again:

Later, we may want to create a function called showWindow("show window"), the role is to display a window on the screen.

Once the function is written(of course the process of writing is the most difficult), we just need to say:"Who will open a window for me", the showWindow function will display a window on the screen for us.

We can also write a displayCharacter("display character") function, the role is for us to display a game character on the screen.

Composition of the function


We have already touched on functions in the previous lesson, which is a very important main function. But we still need to introduce how the composition of a function is.

The following is the semantic structure of the function. This is a template to understand:

Type Function name(parameter)
{
    //Function body, insert instruction here
}

We need to grasp four points about this template:

  1. Function type:corresponding to the output type, it can also be regarded as the type of the function. Similar to variables, functions also have types, which depend on the type of function return value. If a function returns a floating point number(with a decimal point), then naturally we will set the function type to float or double; if it returns an integer, then we will generally set the type to int or long. But we can also create functions that do not return any value.
  2. Function name:This is the name of your function. You can give your function any name, as long as you follow the same rules for naming variables.
  3. The parameters of the function(corresponding to the input):the parameters are located in parentheses after the function name. These parameters are the data that the function will use to do the operation(operation). You can pass in any number of parameters to the function or not.
  4. Function body:Braces specify the start and end range of the function. You can write as many instructions as you want in braces. For the multipleTwo function above, you need to write the relevant operation instruction to multiply the input number by 2.

According to the type of function, functions can be divided into two categories:

  1. A function that returns a value. For such a function, we set its type to the type of the corresponding value(char, int, long, double, etc.).
  2. Functions that do not return any value. Such a function, we set its type to void(void
    Means "empty, invalid").

Create function


Let's use an example to illustrate, using the multipleTwo function we mentioned above:

The input of this function is an integer int, and the output is also a number of type int.

int multipleTwo(int number)
{
    int result = 0;
    result = 2 * number; //We multiply the number provided by 2
    return result; //We will return twice the number
}

This is your first function except main, aren't you proud?

return result; This sentence is generally placed at the end of the function body and is used to return a value. This sentence means:"Function you stop for me, and then return this value." The result here must be of type int, because the function type is int, so the return value must also be of type int.

result This variable is declared/created in the multipleTwo function, so it can only be used in this function, not in another function(such as main), so it is a private variable of the multipleTwo function.

But is the code above the simplest?

No, it can be simplified as follows:

int multipleTwo(int number)
{
    return 2 * number;
}

The code above does the same thing, and it is simpler to write, with only one sentence in the function body.

Generally speaking, the function we write will have multiple variables in order to do the operation, the multipleTwo function is quite simple.

Multiple parameters or no parameters


Multiple parameters

Our multipleTwo function has only one parameter, but we can also create a function with several parameters, such as the following addition function addition:

int addition(int a, int b)
{
    return a + b;
}

As you can see, just use a comma to separate the parameters.

No parameters

Some functions may have no parameters. For example, a function to display Hello("hello"):

void hello()
{
    printf("Hello");
}

As shown above, this function has no parameters. In addition, we can see that we also set the function type to void, so there is no return statement to return a value, so this function also has no return value.

call function


Now let's take a look at a program and review what we learned before.

We need to use our multipleTwo function to calculate the value of a number twice.

We temporarily write the multipleTwo function before the main function. If it is placed after the main function, an error will occur. We will explain why in the following lessons.

#include <stdio.h>

int multipleTwo(int number)
{
    return 2 * number;
}

int main(int argc, char * argv [])
{
    int initial = 0, twice = 0;

    printf("Please enter an integer ...");
    scanf("%d", & initial);

    twice = multipleTwo(initial);
    printf("twice this number is%d \ n", twice);

    return 0;
}

Our program is run from the main function, we already know this.

We first ask the user to enter an integer, pass its value to the multipleTwo function, and assign the return value of the multipleTwo function to the variable twice.

Look carefully at the following line. This is the line of code that we care about the most, because it is this line that calls our multipleTwo function.

twice = multipleTwo(initial);

In parentheses, we pass the variable initial as input to the function. It is also the initial variable that the function will use for its internal processing.

This function returns a value, which we assign to the variable twice.

In fact, in this line, we are the "command" computer:"Let the multipleTwo function calculate the value of twice the initial value for me and store the result in the variable twice."

Detailed step-by-step explanation


Perhaps for beginners, it is still a little difficult to understand.

Don't worry, I believe that through the step-by-step explanation below, everyone will understand more thoroughly.

This specially commented code shows you the running order of the program:

#include <stdio.h>

int multipleTwo(int number) //6
{
    return 2 * number; //7
}

int main(int argc, char * argv []) //1
{
    int initial = 0, twice = 0; //2

    printf("Please enter an integer ..."); //3
    scanf("%d", & initial); //4

    twice = multipleTwo(initial); //5
    printf("twice this number is%d \ n", twice); //8

    return 0; //9
}

The numbers above indicate the order of execution:

1-> 2-> 3-> 4-> 5-> 6-> 7-> 8-> 9

  1. The program starts execution from the main function;
  2. The commands in the main function are executed line by line;
  3. Execute printf output;
  4. Execute scanf to read in the data and assign it to the variable initial;
  5. Read the instruction and call the multipleTwo function, so the program jumps to the above multipleTwo function to execute;
  6. Run the multipleTwo function and accept a number as input(number);
  7. Perform an operation on number and end the multipleTwo function. return means the end of the function and returns a value;
  8. Go back to the next instruction of the main function and output it with printf;
  9. Another return, this time is the end of the main function, so the entire program is finished.

The variable initial is passed to multipleTwo's parameter number(another variable), which is called value passing.

Of course, in fact, the principle is to make a copy of the variable initial and assign the copy to number. This concept of value transfer will be detailed later in the chapter of pointer learning.

Here, if we change the initial name to number, it is also possible, and it will not conflict with the parameter number of the function multipleTwo. Because the parameter number is an exclusive variable belonging to the multipleTwo function.

test program


The following is an example of the program running:

Please enter an integer ... 10
Twice this number is 20

Of course, you don't have to assign the return value of the multipleTwo function to a variable, you can also directly pass the return value of the multipleTwo function to another function, as if multipleTwo(intial) is a variable.

Look carefully at the following program, which is almost the same as above, but the behavior of the last printf is modified, and we did not use the variable twice because it is unnecessary:

#include <stdio.h>

int multipleTwo(int number)
{
    return 2 * number;
}

int main(int argc, char * argv [])
{
    int initial = 0, twice = 0;

    printf("Please enter an integer ...");
    scanf("%d", & initial);

    //The result(return value) of the function is directly passed to the printf function without passing through the third party variable
    printf("twice this number is%d \ n", multipleTwo(initial));

    return 0;
}

We can see that this time the program directly passed the return value of the multipleTwo function to the printf function.

What happens when the program runs to this line?

Very simple, the computer sees this line as the printf function, so it calls the printf function of the standard input and output library and passes all the parameters we give to the printf function.

The first parameter is the statement to be displayed, and the second parameter is an integer.

The computer also knows that to pass this integer value to the printf function, it must first call the multipleTwo function, so it obediently calls the multipleTwo function, doubles the multiplication operation, and directly passes the result to the printf function.

This is a cascading call of functions. The advantage of this is that one function can call another function on demand.

As long as you want, our multipleTwo function can call other functions, as long as you are willing to write. Then this function can also call other functions, and so on.

This is the principle on which C language programs are based. All the codes are grouped together in a planned way, similar to Lego bricks.

Finally, the most difficult thing is to write functions. Once it's done, you just need to call it, and don't need to worry too much about the operations performed inside the function.

Using functions can greatly reduce code repetition. Trust me, you will need functions very much.

3 . Examples of some functions


If you have studied the previous courses together, you should have this impression:I am an "example madman".

Yes, because I like to use examples to deepen understanding.

Because I think theory is good, but if there is only theory, then we can't master knowledge well, and it's a pity that we don't know how to apply it. I remembered the ad phrase "Although Jinjiu is good, don't be greedy" ...

So below we will look at a few examples of functions together, so that readers have a deeper understanding of functions. We try to show different situations so that everyone can see the various types of functions that may appear.

Euro/Chinese Yuan conversion


Let's write a function to convert the euro to the renminbi.

Check the latest exchange rate:1 euro = 7.8553 yuan.

#include <stdio.h>

double conversion(double euros)
{
    double rmb = 0;

    rmb = 7.8553 * euros;
    return rmb;
}

int main(int argc, char * argv [])
{
    printf("10 Euro =%f RMB \ n", conversion(10));
    printf("50 Euro =%f RMB \ n", conversion(50));
    printf("100 Euro =%f RMB \ n", conversion(100));
    printf("200 Euro =%f RMB \ n", conversion(200));

    return 0;
}

You can also write a small program to convert RMB to Euro.

Punishment


Next, look at a function, this function does not return any value, so the type is void. This function will display a certain number of messages on the screen based on the incoming parameters.

This function has only one parameter, and that is to display the number of penalty statements:

#include <stdio.h>

void punish(int lineNumber)
{
    int i;

    for(i = 0; i <lineNumber; i ++)
    {
        printf("I shouldn't be rich and wayward \ n");
    }
}

int main(int argc, char * argv [])
{
    punish(5);

    return 0;
}

The results are as follows:

I shouldn't be rich and capricious
I shouldn't be rich and capricious
I shouldn't be rich and capricious
I shouldn't be rich and capricious
I shouldn't be rich and capricious

Rectangular area


The area of ​​the rectangle is easy to calculate:length x width.
Let's write a function to find the area of ​​a rectangle. It has two parameters:the length of the rectangle and the width of the rectangle. The return value is the area of ​​the rectangle:

#include <stdio.h>

double rectangleArea(double length, double width)
{
    return length * width;
}

int main(int argc, char * argv [])
{
    printf("The rectangular area with a length of 10 and a width of 5 is%f \ n", rectangleArea(10, 5));
    printf("The rectangular area with a length of 3.5 and a width of 2.5 is%f \ n", rectangleArea(3.5, 2.5));
    printf("The rectangular area with a length of 9.7 and a width of 4.2 is%f \ n", rectangleArea(9.7, 4.2));

    return 0;
}

Show results:

The rectangular area with a length of 10 and a width of 5 is 50.000000
The rectangular area with a length of 3.5 and a width of 2.5 is 8.750000
The rectangular area with a length of 9.7 and a width of 4.2 is 40.740000

Can we display the length, width and calculated area directly in the function?

of course can. In this case, the function does not have to return any value. The function calculates the rectangular area and displays it directly on the screen:

#include <stdio.h>

void rectangleArea(double length, double width)
{
    double area = 0;

    area = length * width;
    printf("The area of ​​a rectangle with length%f and width%f is%f \ n", length, width, area);
}

int main(int argc, char * argv [])
{
    rectangleArea(10, 5);
    rectangleArea(3.5, 2.5);
    rectangleArea(9.7, 4.2);

    return 0;
}

We can see that the printf function is called in the function body, and the displayed result is the same as before putting printf in the main function. It's just that we use different methods.


Remember that example of the menu in the previous lesson?("Emperor, do you remember Xia Yuhe by Daming Lake?")

This time we will rewrite it with a custom function, which will be more detailed and optimized:

#include <stdio.h>

int menu()
{
    int choice = 0;

    while(choice <1 || choice> 4)
    {
        printf("Menu:\ n");
        printf("1:Peking duck \ n");
        printf("2:Mapo tofu \ n");
        printf("3:Fish-flavored shredded pork \ n");
        printf("4:Chopped pepper fish head \ n");
        printf("Your choice?");
        scanf("%d", & choice);
    }

    return choice;
}

int main(int argc, char * argv [])
{
    switch(menu())
    {
        case 1:
            printf("You ordered Peking Duck \ n");
            break;
        case 2:
            printf("You ordered Mapo Tofu \ n");
            break;
        case 3:
            printf("You ordered fish-flavored shredded pork \ n");
            break;
        case 4:
            printf("You ordered the fish head \ n");
            break;
    }

    return 0;
}

This program can also be improved:

You can display an error message when the user enters a wrong number instead of continuing to order it.

4 . Summary


  1. The functions can call each other, so the main function can call the functions defined by the C language system, such as scanf and printf, and can also call the functions defined by ourselves.
  2. A function accepts some variables as input, we call it the parameter of the function(the function with void parameter).
  3. The function will use these parameters to do a series of operations, and then use return to return a value(there is also a function without a return value).

5 . The first part of the exercises


Today's class is here, come on!

Next lesson: C language exploration tour | Part I exercises

In the next lesson, let's do some exercises to help consolidate knowledge!


My name is 谢恩铭 , the public number "[Programmer League]( https://github.com/frogoscar/ProgrammerLeague/blob/master/qrcode . "jpg)" operator, elite lecturer Ms. Oscar , a lifelong learner.
Love life, like swimming and have a little understanding of cooking.
Life motto:"Go straight to the benchmark"