[C language] Playing with functions - what you need to know about functions!

Table of contents

foreword

1. What is a function in C language?

2. Classification of functions

2.1 Library functions

2.1.1 What are library functions?

2.1.2 How to learn library functions

2.2 Custom functions

3. Function parameters

3.1 Actual parameters (actual parameters)

3.1 Formal parameters (formal parameters)

4. Function call

4.1 Call by value

4.2 Call by address

5. Nested call and chain access of functions

5.1 Nested use

5.2 Chain access

​edit

6. Function declaration and definition

6.1 Function declaration

6.2 Function definition

6.3 Difference between function declaration and definition

Summarize


foreword

Functions play a huge role in our programming. It is like a function, a move, when we need to use it, we can call it directly to resist the opponent. The use of functions not only makes our code concise, but also makes our code easy to manage. Therefore, when learning programming, mastering the knowledge of functions undoubtedly occupies an important position in our learning.

1. What is a function in C language?

In Wikipedia, the definition of function in C language is: subroutine.
So what is a subroutine?

1. In computer science, a subroutine (English: Subroutine, procedure, function, routine, method, subprogram, callable unit) is a certain part of the code in a large program, consisting of one or more statement blocks. It is responsible for completing a specific task and is relatively independent from other codes.

2. Generally, there are input parameters and return values, which provide the encapsulation of the process and the hiding of details. These codes are often integrated as software libraries.

Extract the point of information from this, "some portion of code in a larger program" "responsible for doing a specific task". For example, when we are making a calculator, we need to add, subtract, multiply and divide four large blocks of content. Here we can make addition into a separate code block, which is specially used to realize the function of addition. This function is a function.

2. Classification of functions

2.1 Library functions

2.1.1 What are library functions?

Library function (Library function) is a way to put functions in the library for others to use. It is to compile some commonly used functions and put them into a file for different people to call. When calling, just add the file name where it is located with #include<>. It is usually placed in the lib file.

Generally, it refers to the functions provided by the compiler that can be called in the C source program.
It can be divided into two categories, one is the library function stipulated by the C language standard, and the other is the compiler-specific library function.

Due to copyright reasons, the source code of the library function is generally not visible, but you can see its external interface in the header file.

for example:

When we are learning C language programming, we always can't wait to know the result after a code is written, and want to print the result to our screen to see. At this time, we will frequently use a function: print information to the screen in a certain format (using the printf function).
In the process of programming, we will frequently do some copying of strings (using the strcpy function).
In programming, we also calculate, and always calculate operations such as n to the kth power (using the pow function).
Like the basic functions we described above, they are not business codes. Every programmer may use it during the development process. In order to support portability and improve program efficiency, the basic library of C language provides a series of similar library functions to facilitate software development by programmers.

2.1.2 How to learn library functions

Here, we can use a necessary website for programmers: http://www.cplusplus.com/

Open, we can see that there are a lot of library functions

insert image description here

Here we take strcpy as an example to explain how to use this website.

The first step is to open the website
The second step is to search for the function strcpy

insert image description here

The third step is to view the function and usage of the function. insert image description here Example code:

#include<stdio.h>
#include<string.h>
int main()
{
	char arr1[20] = { 0 };
	char arr2[] = "gogogo";

	strcpy(arr1, arr2);
	printf("%s\n", arr1);
}

insert image description here

 

I believe that through such a description, everyone can also understand how to use library functions!

Here, a brief summary, the library functions commonly used in C language are:

IO function - input/output function input/output printf scanf getchar putchar
string operation function strlen strcmp strcpy strcat
character operation function tolower toupper
memory operation function memcpy menset memmove memcmp
time date function time
math function sqrt abs fabs pow
other library functions

Note:
But a secret that the library function must know is: to use the library function, the header file corresponding to #include must be included.

Need to learn how to use query tools:
MSDN (Microsoft Developer Network)
www.cplusplus.com
http://en.cppreference.com (English version) http://ch.cppreference.com (Chinese version)

2.2 Custom functions

Have you noticed that library functions cannot solve all problems. For example, today I want to write a program for automatically brushing teeth, and there may be no library functions at all. At this time, we programmers need to define the function themselves.

This is the custom function.
Like library functions, custom functions have function names, return value types, and function parameters.
But the difference is that these are all designed by ourselves. This gives programmers a lot of freedom to play.

ret_type fun_name(para1, * )
{ statement;//statement item }

ret_type return type
fun_name function name
para1 function parameter

for example:

Write a function to find the maximum of two integers

#include <stdio.h>
//get_max函数的设计
int get_max(int x, int y) 
{
 return (x>y)?(x):(y);
}
int main()
{
 int num1 = 10;
 int num2 = 20;
 int max = get_max(num1, num2);//调用函数
 printf("max = %d\n", max);
 return 0; 
 }

3. Function parameters

3.1 Actual parameters (actual parameters)

When calling a function with parameters, there is a data transfer relationship between the calling function and the called function.
When calling a function in the calling function, the parameters in parentheses after the function name are called "actual parameters" (referred to as "actual parameters").
Actual parameters can be constants, variables or expressions. No matter what type of quantity the actual parameters are, they must have definite values ​​when the function is called, so that these values ​​can be transferred to the formal parameters. Therefore, methods such as assignment and input should be used in advance to obtain a definite value for the actual parameter.

for example:

#include <stdio.h>
void Swap1(int x, int y)
 {
 int tmp = 0;
 tmp = x;
 x = y;
 y = tmp; }
void Swap2(int *px, int *py) {
 int tmp = 0;
 tmp = *px;
 *px = *py;
 *py = tmp; }
int main()
{
 int num1 = 1;
 int num2 = 2;
 Swap1(num1, num2);//实参可以是常量、变量或表达式
 printf("Swap1::num1 = %d num2 = %d\n", num1, num2);
 Swap2(&num1, &num2);//实参可以是常量、变量或表达式
 printf("Swap2::num1 = %d num2 = %d\n", num1, num2);
 return 0; }

3.1 Formal parameters (formal parameters)

Formal parameters refer to the variables in parentheses after the function name, because formal parameters are only instantiated (allocated memory units) when the function is called, so they are called formal parameters.
Formal parameters are automatically destroyed when the function call completes. Therefore formal parameters are only valid within the function.

The parameters x, y, px, py in the Swap1 and Swap2 functions above are all formal parameters.
The num1, num2 passed to Swap1 in the main function and &num1, &num2 passed to the Swap2 function are the actual parameters.

Here we analyze the actual parameters and formal parameters of the function,
borrowing a picture from the Internet

insert image description here

The actual parameter is the specific data passed by the calling function. Actual parameters are always passed one-way to formal parameter data. In memory cells are different cells.

In the above Swap1 function, the values ​​of formal parameters x and y have changed during the call, but in the main function, the values ​​of num1 and num2 have not changed. So the transfer of the actual parameter to the value of the formal parameter is one-way.

For the Swap2 function, since the address is also passed, both values ​​are changed, which is also the call by value and call by reference mentioned below.

**[Note]** After the formal parameter is instantiated, it is actually equivalent to a temporary copy of the actual parameter.

4. Function call

4.1 Call by value

The formal parameters and actual parameters of the function occupy different memory blocks, and the modification of the formal parameters will not affect the actual parameters.

For example, swap the values ​​of two integers.

#include <stdio.h>


int Swap(int x, int y)//这里形参x,y占据的内存块与下面实参a,b占据的内存块是不同的
{
	int z = 0;
	z= x;
	x= y;
	y = z;
}

int main()
{
	int a = 10;
	int b = 20;
	printf("交换前a=%d,b=%d\n", a, b);
	Swap(a, b);//这里实参a,b占据的内存块与上面形参x,y占据的内存块是不同的
	printf("交换后a=%d,b=%d\n", a, b);
	return 0;
}

insert image description here

We can see that the values ​​of a and b have not changed here, because the formal parameters and actual parameters of the ** function occupy different memory blocks, and the modification of the formal parameters will not affect the actual parameters. **So, when the actual parameters a and b are passed to the formal parameters x and y, the formal parameters are a temporary copy of the actual parameters. Changing the formal parameter variables x and y will not affect the actual parameters a and b.

4.2 Call by address

1. Call by address is a way to call a function by passing the memory address of the variable created outside the function to the function parameter.
2. This way of passing parameters can establish a real connection between the function and the variables outside the function, that is, the inside of the function can directly manipulate the variables outside the function.

For example, also swap the values ​​of two integers

#include<stdio.h>
void Swap(int *px, int *py)//用指针接收a,b的地址
{
	int z = 0;
	z = *px;
	*px = *py;
	*py = z;
}

int main()
{
	int a = 10;
	int b = 20;
	printf("交换前a=%d,b=%d\n", a, b);
	Swap(&a,&b);//把a,b的地址传到上面函数去
	printf("交换后a=%d,b=%d\n", a, b);
	return 0;
}

insert image description here

Here, we can understand that if the memory addresses of a and b are passed to the function, in the function, we can pass the data back according to the pointer address. Let the function establish a real connection with the variables outside the function, that is, the inside of the function can directly manipulate the variables outside the function.

5. Nested call and chain access of functions

5.1 Nested use

It should be noted that nested function definitions are not allowed in C language . Therefore, the functions are parallel, and there is no problem of upper-level functions and lower-level functions. But the C language allows a call to another function in the definition of a function. In this way, nested calls of functions appear. That is, other functions are called in the called function.

for example:

void first_line()
{
	printf("hello world\n");
}
void two_line()
{
	int i = 0;
	first_line();
}
int main()
{
	two_line();
	return 0;
}

insert image description here

 The main function calls the two_line function, and the two_line function calls the first_line function. When a function calls a function, we say it is a nested call of a function
** Note that ** functions can be called nestedly, but they cannot be defined nestedly.
What's the meaning?
That is, we cannot define a function within a function, for example:

insert image description here

5.2 Chain access

Use the return value of one function as an argument to another function.

Let's take an example.

#include <stdio.h>
int main()
{
    printf("%d\n", printf("%d", printf("%d", 43)));
    //注:printf函数的返回值是打印在屏幕上字符的个数
    return 0; }

insert image description here

6. Function declaration and definition

6.1 Function declaration

1. Tell the compiler what a function is called, what its parameters are, and what its return type is. But whether it exists or not, the function declaration cannot decide.
2. The declaration of the function generally appears before the use of the function. It must be declared before use.
3. The declaration of the function should generally be placed in the header file.


The format of a function declaration:

dataType functionName( dataType1 param1, dataType2 param2 … );

With function declarations, function definitions can appear anywhere, even other files, static link libraries, dynamic link libraries, etc.

In simple terms, the function of "function declaration" is to inform the compilation system of the name, function type, and formal parameter type, number, and order of the function, so that the system can check it accordingly when calling the function (for example, whether the function name is correct, Whether the type and number of actual participation formal parameters are consistent)

6.2 Function definition

The definition of a function refers to the specific realization of the function, explaining the function realization of the function.

​
void Swap1(int *px, int *py);//函数的声明
void Swap(int *px, int *py)//函数定义
{
	int z = 0;
	z = *px;
	*px = *py;
	*py = z;
}
int main()
{
	int a = 10;
	int b = 20;
	printf("交换前a=%d,b=%d\n", a, b);
	Swap(&a,&b);
	printf("交换后a=%d,b=%d\n", a, b);
	return 0;
}

​

6.3 Difference between function declaration and definition

1. The declaration of a function is very similar to the definition of a function in form, but the two are essentially different. The declaration does not open up memory, but only tells the compiler that the part to be declared exists, and a little space should be reserved. Definition requires memory allocation.

Function Definition
A function definition is a complete functional unit:

包含函数类型、函数名、形参及形参类型、函数体等
在程序中,函数的定义只能有一次
函数首部与花括号间不加分号

Function declaration
A function declaration is just a description of the compilation system:

函数声明是对定义的函数的返回值的类型说明,以通知系统在本函数中所调用的函数是什么类型。
不包含函数体(或形参)
调用几次该函数就应在各个主调函数中做相应声明
函数声明是一个说明语句,必须以分号结束!

Summarize

Functions have a lot of other knowledge, this article is just a brief discussion. Functions play an important role in our programming. Only by learning functions well can we make better progress in the next study.

Thank you for your support. If there are any mistakes in the article, please correct me, thank you.

Guess you like

Origin blog.csdn.net/lm_love_hxl/article/details/130309006