当前位置:网站首页>Function related knowledge
Function related knowledge
2022-07-28 00:56:00 【Xu Hanhan!】
We have learned about branch and loop statements , Today we will learn a new chapter —— function , We're getting to know each other C Language has written a function to get the maximum value of two integer variables , Today, let's study what a function is and how it executes .
Catalog :
1. What is a function2. Library function3. Custom function4. Function parameter5. Function call6. Nested calls and chained access to functions7. Function declaration and definition8. Function recursion ( We will write another blog about function recursion )
One · function
1.1 What is a function ?
We all know , A program must have main Function this body , This main Function is a main function , There can only be one in a project main function , We are main Write the statement items we need in the function , When we want to be in main When some functions are performed in the function , We will adopt the method of function encapsulation , So functions can also be called subroutines , It is a code block to complete the required functions .
1.2 C Classification of language functions
C Functions in languages are generally divided into library functions and user-defined functions . Where the library function is C What language itself has , When we write code, we just need to call ( When calling, you need to reference the header file ), however C Language cannot contain all functions , Because each programmer has different functions and needs , Therefore, the writing of user-defined functions is also particularly important for us .
Here I will explain the implementation functions of two library functions :
1.strcpy( String copy function )
Function model :char * strcpy ( char * destination, const char * source );
The function is to copy the contents of one string to another , Pay attention to the position of parameters , The copied string is used as the first parameter of the function
//strcpy Implementation of function
int main()
{
char arr1[10] = "abcdef";
char arr2[10] = { 0 };
strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
2.memset( Memory setting function )
Function model :
void * memset ( void * ptr, int value, size_t num );
The function of this function is to start with the number of characters in the target array ( I.e. pointer ) backward num Bytes are set to value
int main()
{
char arr1[] = "hello world!";
char arr2[] = "############";
memset(arr2, 'X', 5);
printf("%s\n", arr2);
return 0;
}
1.3 How to learn library functions ?
C There are many library functions in the language , According to the parameters in each function model, we can roughly guess the function performed by the library function and the type of parameters , But how can we accurately know the implementation and examples of each library function ? Here I give you several websites to learn about library functions .
1.MSDN(Microsoft Developer Network) Go to the official website to download or send you the installation package by private mail
2.www.cplusplus.com
3.http://en.cppreference.com( English version )
4. http://zh.cppreference.com ( Chinese version )
1.4 Custom function
I learned the use of library functions briefly above , The use and execution of custom functions are the main objectives of our study , Otherwise, what do we programmers do !
First, let's take a look at the composition of custom functions
ret_type fun_name(para1, * ){statement;// Statement item}ret_type Return typefun_name Function namepara1 Function parameter
Practice is the only criterion for testing truth , Let's give an example to illustrate in detail : Write a function to find the maximum value of two integers .
int get_max(int x, int y)
{
return ((x > y) ? x : y);
}
int main()
{
int x = 0;
int y = 0;
scanf("%d %d", &x, &y);
int max = get_max(x, y);
printf("%d\n", max);
return 0;
}
There are compilation results , We got 10 20 The larger value between is 20, Let's write a get_max Function to perform this function , Its return type is int, Because we define a in the main function int Variable of type max To accept the return value after the function is executed
Let's give you another example : Write a function to exchange the contents of two shaping variables
// Implemented as a function , But I can't finish the task
void Swap1(int x, int y) {
int tmp = 0;
tmp = x;
x = y;
y = tmp;
}
// The right version
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;
}
Here I have written two versions Swap1 and Swap2 function , among Swap1 Functions pass variables num1 and num2, and Swap2 Functions pass variables num1 and num2 The address of , Why the compilation result of the former is wrong , The compilation result of the latter is correct ?
as a result of :
When we put variables num When the value of is passed to the function , A new variable will be created to accept the passed value , But the memory space occupied by the newly created variable and the variable passed to the function is different ( The implication is that the two variables are only numerically equal ), Therefore, the modification of the new variable will not change the variable num Value , So we can simply think that : After the formal parameter is instantiated, it is actually equivalent to a temporary copy of the argument .
Two · The parameters of the function
2.1 The actual parameter ( Actual parameters ):
2.2 Formal parameters ( Shape parameter ):
3、 ... and · Function call
3.1 Value transfer call
3.2 Address call
3.3 practice
1. Print 100-200 The prime between
//1. Normal version
int is_prime(int i)
{
int j = 0;
// use 2-i-1 To try division i
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
return 0;
}
}
return 1;
}
int main()
{
int count = 0;// Count
int i = 0;
for (i = 100; i <= 200; i++)
{
// If it is a prime number, return 1 Otherwise return to 0
if (is_prime(i))
{
printf("%d ", i);
count++;
}
}
printf("\n count = %d\n", count);
return 0;
}
//2. Optimized version
#include <math.h>
int is_prime(int i)
{
int j = 0;
// use 2-i-1 To try division i
for (j = 2; j <= sqrt(i); j++)
{
if (i % j == 0)
{
return 0;
}
}
return 1;
}
int main()
{
int count = 0;// Count
int i = 0;
for (i = 100; i <= 200; i++)
{
// If it is a prime number, return 1 Otherwise return to 0
if (is_prime(i))
{
printf("%d ", i);
count++;
}
}
printf("\n count = %d\n", count);
return 0;
} 
The optimized version uses sqrt This function , Readers may consult by themselves , Need to reference header file math.h
2. Print 1000-2000 Leap year between
// Leap year
//1. Can be 4 Divisible but not by 100 Divisible number
//2. Can be 400 Divisible number
int is_leap_year(int i)
{
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int count = 0;// Count
int year = 0;
for (year = 1000; year <= 2000; year++)
{
// If it is a leap year, return 1 Otherwise return to 0
if (is_leap_year(year))
{
printf("%d ", year);
count++;
}
}
printf("\n count = %d\n", count);
return 0;
}
3. Write a function , To realize binary search of an ordered array
int Binary_search(int arr[],int k, int sz)
{
int left = 0;
int right = sz - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] < k)
{
left = mid + 1;
}
else if (arr[mid] > k)
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int k = 7;// Suppose the number you need to find is 7
int sz = sizeof(arr) / sizeof(arr[0]);
// If the search is successful, the subscript is returned, otherwise -1
int ret = Binary_search(arr,k, sz);
if (ret != -1)
{
printf(" Subscript to be :%d\n", ret);
}
else
{
printf(" Did not find \n");
}
return 0;
}
What needs to be noted is , Size of array sz It must be calculated in the main function and passed to the lookup function , Because the address of the first element of the array is passed when the array passes parameters, not the entire array
4. Write a function , Every time you call this function , Will be num The value of the increase 1
// Address call
void Add(int* p)
{
int z = *p;
(*p)++;
return z;
}
int main()
{
int num = 0;
Add(&num);// Because you need to change num Value , Therefore, address calling is adopted
printf("%d\n", num);
Add(&num);
printf("%d\n", num);
Add(&num);
printf("%d\n", num);
return 0;
}
// Value transfer call
int Add(int num)
{
return (++num);// Notice that this is ++num instead of num++
}
int main()
{
int num = 0;
num = Add(num);// The value returned each time is num receive
printf("%d\n", num);
num = Add(num);
printf("%d\n", num);
num = Add(num);
printf("%d\n", num);
return 0;
}
Four · Nested calls and chained access to functions
4.1 Nested calls
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;
}
We call... In the main function three_line function , stay three_line Call in function new_line function , The operation of calling a function in a function is called nested call of a function , So the results are printed as three hehe
Be careful : Functions can be called nested , But you can't nest definitions , Because for any function , The status is equal , You cannot define another function in a function
4.2 Chained access
Example 1:
#include <string.h>
int main()
{
char arr[] = "abcdef";
printf("%d\n", strlen(arr));
return 0;
}
The obvious result is 6,strlen Is a function that calculates the length of a string , We will strlen The result of function execution is placed in printf Function is printed , This is the chained access of functions
Example 2:
int main()
{
printf("%d", printf("%d", printf("%d", 43)));
// The result is what ?
// notes :printf The return value of the function is the number of characters printed on the screen
return 0;
}
among printf The return value of the function is the number of characters printed on the screen , As a result, the reader understands
5、 ... and · Function declaration and definition
5.1 Declaration of functions
5.2 Definition of function
In the function part, we only have one function recursion , Because the recursion of functions is difficult , I will write a separate blog to explain . I hope you can digest and absorb the content of today's function , come on. , Thank you for your support !!!
边栏推荐
- 递归求解迷宫问题
- Leetcode 452. minimum number of arrows to burst balloons (medium)
- Data visualization - White Snake 2: black snake robbery (3)
- 为华为打造无美系设备的产线,台积电三星能做到吗?
- Ali Er Mian: why do we need to separate databases and tables?
- Jericho will make a popping sound when turning on, broadcasting a prompt tone, and turning off [chapter]
- How does matlab set the K-line diagram to classic red and green color matching?
- ASML推出第一代HMI多光束检测机:速度提升600%,适用于5nm及更先进工艺
- 网络设备硬核技术内幕 防火墙与安全网关篇 (五) 安全双修大法 中
- Network device hard core technology insider firewall and security gateway (summary)
猜你喜欢

"C language" deep entry rounding & four functions

点分治解析

Buildforge materials

Resolved Unicode decodeerror: 'UTF-8' codec can't decode byte 0xa1 in position 0: invalid start byte

Point divide and conquer analysis

Set 数据构造函数

mysql数据库的基本操作(二)-——基于数据表

【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发

小波变换学习笔记
![Jerry Zhi doesn't play hidden audio files [article]](/img/09/b9fb293151f56d2a93f8a1c8f3d0dc.png)
Jerry Zhi doesn't play hidden audio files [article]
随机推荐
怎么清晰地理解、表达 IaaS 、 PaaS 、 SaaS ?
2020年一季度可穿戴市场出货量达7260万部,苹果独占近三成市场份额
Jerry's PWM setting and PWM IO selection [chapter]
Basic operations of MySQL database (I) --- Based on Database
Border width border fillet border color
【C语言入门】ZZULIOJ 1026-1030
Buildforge materials
Network device hard core technology insider firewall and security gateway (VIII) virtualization artifact (middle)
【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发
估值360亿美元!即将进行首次载人发射的SpaceX筹资3.46亿美元
Valued at $36billion! SpaceX, which is about to launch its first manned launch, raised $346million
Selection of FFT sampling frequency and sampling points
7. Typescript part Foundation
LeetCode_ Bit operation_ Medium_ 137. Number II that appears only once
At least 42 employees are infected with novel coronavirus! Nokia announces closure of telecom equipment plant in India
【OpenCV 例程 300篇】241. 尺度不变特征变换(SIFT)
网络设备硬核技术内幕 防火墙与安全网关篇 (十二) 零接触办公的奥秘 下
uniapp显示富文本效果demo(整理)
In the first quarter of 2020, the wearable market shipped 72.6 million units, with apple occupying nearly 30% of the market share
592. Fraction addition and subtraction: introduction to expression calculation