Author Xie Enming, public number “programmer union”. Please indicate the source of reprint. Original: www.jianshu.com/p/148564646…
The whole series of C language Exploration
Content abstract
- preface
- Function creation and invocation
- Some examples of functions
- conclusion
- The first part of the exercise notice
1. Introduction
A lesson is the first part of the C language to explore trip | lesson 10: the first C language games.
In this lesson we will conclude the first part of the C exploration Tour (the basics) with the focus on functions, and the second part will welcome us to the advanced technology of C.
The second part will be difficult, but don’t worry, we will learn step by step, little by little. C is not at all scary as long as it is directed in the right direction and takes the time.
In this lesson we will also explain the principles on which C programs are based.
We’re going to learn how to manage programs in pieces, kind of like Lego bricks.
In fact, all large C programs are collections of small program blocks, which we call functions. = Function = function = function [number] function.
In object-oriented languages such as Java and C++, functions are also called methods. Of course, we are only talking about C (procedural language), not object-oriented language.
2. Function creation and invocation
As we learned in previous lessons, all C programs start with the main function. At that time we also showed a summary diagram with some terms in it:
The top part, which we call “preprocessing instructions,” is easy to identify because it starts with a # and is usually placed at the top of the program.
The following sections are the functions to be studied, in this case the main function.
As mentioned earlier, the C language uses the main function as the entry function. To run a C program, you must have the main function. Except, all the programs we’ve written so far, including the little game we played last time, have just been tinkering inside main, we haven’t gotten out of main yet.
You might ask, “Isn’t that a good idea?”
The answer is: not that it’s bad, but it’s not what C programmers usually do. Few programmers write code just inside curly braces of main.
So far the programs we’ve written have been pretty small, but imagine if the programs got really big, with thousands, tens of thousands, or even millions of lines of code. Would we want to cram all that code into main?
So let’s learn how to better plan our program. We’re going to learn how to break the program up into small pieces, like the pieces of a Lego block, that can be put together to form a lot of interesting shapes.
These little pieces of program we call functions.
A function performs some operation and returns a value. A program is a sequence of code that performs a specific task.
A function has inputs and outputs, as shown below:
We can think of the function as a sausage machine, where you put a pig in the input end, and the sausage comes out of the output end. This sour cool, self-evident ~
When we call a function in a program, three steps occur:
- Input: Passing some information to a function (by giving the function some arguments).
- Operations: Functions can perform specific tasks using information passed in from the input.
- Output: After the operation, the function returns a result called the output or return value.
For example, let’s say we have a function called multipleTwo that doubles the input as follows:
The purpose of the function is to make the source code more structured and to save the source code because we don’t have to type the same snippet every time we just call the function.
Now consider this:
Then we might want to create a function called showWindow, which displays a window on the screen.
Once the function is written (which is the hardest part), we can just say “somebody, open a window for me” and the showWindow function will display a window for us on the screen.
We can also write a displayCharacter function that displays a game character on the screen for us.
Composition of functions
We’ve already touched on functions in previous lectures, the very important main function. But we need to talk a little bit about what a function looks like.
Here is the structure of the semantics of functions, which is a template to know:
Type function name (argument) {// Function body, insert instruction here}Copy the code
There are four things to know about this template:
-
Function type: Corresponds to the output type, which can also be regarded as the type of a function. Like variables, functions have types, which depend on the type of the value returned by the function. If a function returns a floating-point number (with a decimal point), it is natural to type the function as float or double; If an integer is returned, then we would typically make the type int or long. But we can also create functions that do not return any value.
-
Function name: This is the name of your function. You can name your functions whatever you want, as long as you follow the same rules for naming variables.
-
Parameters of a function (corresponding to input) : Parameters are enclosed in parentheses after the function name. These parameters are the data that the function uses to perform operations. You can pass any number of arguments to a function, or you can pass no arguments at all.
-
Function body: Curly braces specify the start and end ranges of a function. You can write as many instructions as you want inside curly braces. For the multipleTwo function above, we need to write instructions to multiply the input number by two.
Functions can be divided into two classes based on their type:
-
A function that returns a value. For such functions, we assign the type of the corresponding value (char, int, long, double, etc.).
-
A function that does not return any value. Such a function is of type void (void stands for “empty, invalid”).
Create a function
As an example, use the multipleTwo function we mentioned above:
The input of this function is an int and the output is an int.
int multipleTwo(int number) { int result = 0; result = 2 * number; // We multiply the supplied number by 2returnresult; // We return 2 times the number}Copy the code
This is your first function other than main, proud of it?
return result; This sentence is usually placed at the end of the function body and is used to return a value. This means: “You stop the function and return this value.” The result must be of type int, and since the function type is int, the return value must also be of type int.
The result variable is declared/created in multipleTwo, so it can only be used in that function, not in another function (such as main), so it is a private variable of multipleTwo.
But is the above code the simplest?
No, it can be simplified as follows:
int multipleTwo(int number)
{
return 2 * number;
}
Copy the code
The above code does the same thing and is much simpler to write, with only one sentence inside the function.
Normally, we write functions that have multiple variables so we can do operations, so multipleTwo is pretty simple.
Multiple arguments, or no arguments
Multiple parameters
Our multipleTwo function has only one argument, but we can also create functions with several arguments, such as the following addition function in addition:
int addition(int a, int b)
{
return a + b;
}
Copy the code
As you can see, you only need to separate the parameters with a comma.
No parameters
Some functions may have no arguments. For example, a function that displays Hello:
void hello()
{
printf("Hello");
}
Copy the code
As shown above, this function takes no arguments. In addition, you can see that the function type is void, so there is no return statement to return a value, so the function does not return a value.
Call a function
Now let’s look at a program, just to review what we’ve learned.
We’re going to use our multipleTwo function to compute twice the value of a number.
We’ll write multipleTwo before main for the moment, but if you put it after main it will make an error, and we’ll explain why later in the class.
#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;
}
Copy the code
We already know that our program starts from main.
We first ask the user to input an integer, pass its value to multipleTwo, and assign the return value of multipleTwo to the variable Twice.
Take a closer look at the following line, which is the one we care about most, because it is this line that calls our multipleTwo function.
twice = multipleTwo(initial);
Copy the code
In parentheses, we pass the variable initial as input to the function. It is the variable initial that the function will use for its internal processing.
This function returns a value that we assign to the variable twice.
In this line, we are the “command” computer: “Have multipleTwo compute twice the value of initial 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 you will understand more clearly through the following step-by-step explanation.
This specially commented code shows the order in which the program is run:
#include <stdio.h>
int multipleTwo(int number) // 6
{
return2 * number; // 7 } int main(int argc, char *argv[]) // 1 { int initial = 0, twice = 0; / / 2printf("Please enter an integer... "); // 3
scanf("%d", &initial); // 4 twice = multipleTwo(initial); / / 5printf("Twice this number is %d\n.", twice); / / 8return 0; // 9
}
Copy the code
The numbers above indicate the order of execution:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
-
The program starts with the main function;
-
Commands in main are executed line by line;
-
Execute printf;
-
Execute scanf to read in the data and assign to variable initial;
-
The multipleTwo function is called, so the program jumps to the above multipleTwo function to execute;
-
Run multipleTwo and take a number as input.
-
Operates on number and terminates multipleTwo. Return means the end of a function and returns a value;
-
Go back to the next instruction in main, print it as printf;
-
Another return, this time the end of main, completes the program.
The variable initial, which is passed to number (another variable) in multipleTwo, is called value passing.
Of course, the actual principle is to make a copy of the variable initial and assign the copy to number. The concept of value passing will be discussed later in the chapter on Pointers.
If we rename initial to number, it will not conflict with number in multipleTwo. Because number is a variable that belongs exclusively to multipleTwo.
The test program
Here is an example of the program in action:
Please enter an integer... Twice the number 10 is 20Copy the code
Of course, you do not have to assign the return value of multipleTwo to one variable. You can also pass the return value of multipleTwo directly to another function, just as if multipleTwo(intial) were a variable.
If you look closely at the following program, it is almost the same as above, but we have modified the behavior of the last printf. We also do not use twice because it is not necessary:
#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 passed directly toprintfFunction without passing a third party variableprintf("Twice this number is %d\n.", multipleTwo(initial));
return 0;
}
Copy the code
As you can see, this program passes the return value of multipleTwo directly to printf.
What happens when the program runs to this line?
Very simple, the computer sees that this line is a printf function, so it calls printf in the standard I/O library, and passes in all the arguments that we’ve given to printf.
The first argument is the statement to display, and the second argument is an integer.
The computer knows that in order to pass this integer to printf, it must call multipleTwo, so it obediently calls multipleTwo, does the double multiplication, and passes the result directly to printf.
This is the cascading call of functions, which has the advantage that one function can call another function as needed.
Our multipleTwo function can also call other functions if you want, if you write it. This function can then call other functions, and so on.
This is the principle on which C programs are based. All the code is programmed together, like Lego blocks.
Finally, the hardest part, of course, is writing the function. Once that’s done, you just need to call it and don’t worry too much about what’s going on inside the function.
Using functions can greatly reduce code duplication. Trust me, you’re going to really need functions.
3. Examples of some functions
If you’ve taken a previous class together, you might get the impression that I’m an example maniac.
Yes, because I really like to use examples to deepen my understanding.
Because I think theory is good, but if there is only theory, then we can not have a good grasp of knowledge, and do not know how to apply, that is a pity. Think of the “strong wine is good, but do not drink oh” that advertising words…
So let’s take a look at some examples of functions to give the reader a deeper understanding of them. We try to show different cases so that you can see the different types of functions that can occur.
Euro/RMB conversion
Let’s write a function to convert euros to RMB.
Checked the latest exchange rate: 1 euro = 7.8553 renminbi.
#include <stdio.h>
double conversion(double euros)
{
double rmb = 0;
rmb = 7.8553 * euros;
return rmb;
}
int main(int argc, char *argv[])
{
printf("10 euros = %f RMB \n", conversion(10));
printf("50 euros = %f RMB \n", conversion(50));
printf("100 Euros = %f RMB \n", conversion(100));
printf("200 euros = %f RMB \n", conversion(200));
return 0;
}
Copy the code
You can also write a small program to convert RMB into euros.
punishment
Next, look at a function that does not return any value, so the type is void. This function displays information on the screen a certain number of times based on the parameters passed in.
This function takes only one argument, which displays 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 capricious \n");
}
}
int main(int argc, char *argv[])
{
punish(5);
return 0;
}
Copy the code
The following information is displayed:
I shouldn't be rich and headstrong. I shouldn't be rich and headstrongCopy the code
The rectangular area
The area of a rectangle is easy to calculate: length x width. Let’s write a function to find the area of a rectangle that takes two arguments: its length and its width. 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 area of a rectangle of length 10 and width 5 is %f\n", rectangleArea(10, 5));
printf("The area of a rectangle whose length is 3.5 and width 2.5 is %f\n", rectangleArea (3.5, 2.5));printf("The area of a rectangle whose length is 9.7 and width is 4.2 is %f\n", rectangleArea (9.7, 4.2));return 0;
}
Copy the code
Display result:
A rectangle with a length of 10 and a width of 5 has an area of 50.000000 and a length of 3.5 and a width of 2.5 has an area of 8.750000 and a length of 9.7 and a width of 4.2 has an area of 40.740000Copy the code
Can we just display the length, width and calculated area in the function?
B: Sure. In this case, the function doesn’t have to return any value, it calculates the area of the rectangle 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 of 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;
}
Copy the code
As you can see, printf is called inside the body of the function, and the result is the same as when we put printf inside main. We just do it differently.
The menu
Remember the menu example from the previous lecture? (” Your Majesty, do you still remember the summer rain lotus beside daming Lake?” )
This time we use a custom function to rewrite again, 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: Shredded pork with fish flavor \ N");
printf("4: Chopped fish head with pepper \ N");
printf("What is 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 shredded pork with fish flavor \n");
break;
case 4:
printf("You ordered the fish head with chopped pepper \n");
break;
}
return 0;
}
Copy the code
This program can also be improved:
You can display an error message when the user enters a wrong number, rather than continuing the order.
4. To summarize
-
Functions can call each other, so main can call functions defined by the C language system, such as scanf and printf, as well as our own functions.
-
A function takes some variables as input, which we call arguments to the function (also functions with void arguments).
-
Functions do a series of operations with these parameters, and then return a value (or a function that does not return a value).
5. The first part of the exercise notice
That’s all for today’s lesson, come on!
The next lesson: the first part of C language to explore trip | exercises
Next lesson, let’s do some exercises to help consolidate the knowledge.
I am Xie Enming, the operator of the public account “Programmer Union”, and the moOCs elite lecturer Oscar, a lifelong learner. Love life, like swimming, a little cooking. Life motto: “Run straight for the pole”