当前位置:网站首页>Function - (C travel notes)
Function - (C travel notes)
2022-07-29 09:54:00 【Small Saimao】
Preface
“ There is always one or two winds in the world ,
Fill in my 18000 dreams ”
author : Little Saimao
Article first date :2022/7/24
Catalog
2.C Classification of functions in language
3. The parameters of the function
3.1 The actual parameter ( Actual parameters ):
3.2 Formal parameters ( Shape parameter ):
Write a function to judge whether a number is a prime number
Write a function to determine whether a year is a leap year
Write a function , To realize binary search of an ordered array
Write a function , Every time you call this function , Will be num The value of the increase 1

1. What is a function ?
When it comes to functions, many friends , It will be associated with the concept of function we often see in Mathematics , But what are the functions in the program ?
Wikipedia definition of function : Subroutines
2.C Classification of functions in language
What we are learning at this stage C In language , Functions are divided into :
- Library function
- Custom function
2.1 Library function
In daily life , Our common printf、scanf、strlen And so on are library functions , At this time, some friends will ask questions , Why do we need library functions ? In fact, in the early days C There is no library function in language , This is because without library functions, different people may name themselves many different names for the implementation of a function 、 A variety of implementation methods are used , That's what happened :
- Code redundancy
- n Low development efficiency
- Nonstandard
At this time , Implement some commonly used functions into functions , Integration as library , from C The language directly provides ~ then C Language standards , You can specify the standard of library functions , This practice makes it convenient for programmers to develop software .
So how to learn library functions ?
Here we have a simple look :https://cplusplus.com/
2.2 Custom function
There are many friends , It's time to ask questions again , Why is there a library function , There are also custom functions ?
Here is a very good saying : If library functions can do everything , What do programmers do ?
So we are more interested in Custom function
Custom functions are the same as library functions , There's a function name , Return type and function parameters .
But the difference is that these are designed by ourselves , This gives programmers a lot of room to play
Here, let's take chestnuts :
// Write a function to find the maximum value of two integers
// Write a function to find the maximum value of two integers get_max(int x, int y) { x > y ? x : y; } int main() { int a = 0; int b = 0; scanf("%d %d", &a, &b); // Use the function to find a and b The greater of //Max; int m = get_max(a,b); printf("%d", m); return 0; }// Writing a function can exchange two integers
First, let's think about how to implement this function :
Let's write such a piece of code first :
// Writing a function can exchange two integers // Shape parameter void swap(int x, int y) { int tmp = 0; tmp = x; x = y; y = tmp; } int main() { int a = 0; int b = 0; scanf("%d %d", &a, &b); printf(" Exchange before :a=%d,b=%d\n", a, b); // Actual parameters swap(a, b); printf(" After exchanging :a=%d,b=%d\n", a, b); return 0; }CTRL+f5 Code to go , What we found out was that
Obviously, our program appeared bug, So where is the problem ?
Here we can use debugging and monitoring to see :
Keep pressing f10 Enter two values
Through the analysis of , We can see that x And y With independent space exchange is x And y Value ,a and b The value of has not changed
What about here? , We should know a、b It's called an argument ,x、y It's called a formal parameter , We also come to a conclusion :
When an argument is passed to a formal parameter , A formal parameter is a temporary copy of an argument , Modification of a parameter does not affect the argument .
When we know this , Next we will modify our code :
It's not hard to see. , We can use the pointer method to find the address , Indirect modification . With this idea , We Then we can modify our code :
// Shape parameter void swap1(int x, int y) { int tmp = 0; tmp = x; x = y; y = tmp; } swap2(int* pa, int* pb) { int tmp = *pa; *pa = *pb; *pb = tmp; } int main() { int a = 0; int b = 0; scanf("%d %d", &a, &b); printf(" Exchange before :a=%d,b=%d\n", a, b); // Actual parameters //swap1(a, b); swap2(&a, &b); printf(" After exchanging :a=%d,b=%d\n", a, b); return 0; }Code run results :
3. The parameters of the function
3.1 The actual parameter ( Actual parameters ):
Parameters that are actually passed to the function , It's called the actual parameter .
The argument can be : Constant 、 Variable 、 expression 、 Functions, etc .
Whatever the type of argument is , When you make a function call , They all have to have certain values , In order to pass these values to the formal parameters .
3.2 Formal parameters ( Shape parameter ):
Formal parameters refer to the variables in brackets after the function name , Because formal parameters are only instantiated when the function is called ( Allocate memory units ), So it's called formal parameter . Formal parameters are automatically destroyed when the function call is completed . So formal parameters are only valid in functions .
above Swap1 and Swap2 Parameters in function x,y,px,py All are Formal parameters . stay main Function passed to Swap1 Of num1 , num2 He Zhuan to Swap2 Functional &num1 , &num2 yes The actual parameter .Here we analyze the real and formal parameters of the function :The memory allocation corresponding to the code is as follows :
Here you can see Swap1 When the function is called , x , y Have your own space , As like as two peas, the same thing is true. .
So we can simply think that : After the formal parameter is instantiated, it is actually equivalent to a temporary copy of the argument .4. Function call
Function calls are generally divided into two types
- Value transfer call
The formal and actual parameters of a function occupy different memory blocks , Modification of a parameter does not affect the argument .- Address call
Address call is a way to call a function by passing the memory address of the created variable outside the function to the function parameter .This parameter transfer method can establish a real relationship between the function and the variables outside the function , That is, you can directly operate inside the functionAs a variable outside the function .As mentioned above swap1 In fact, it is called by value ,swap2 Address callingpractice
Write a function to judge whether a number is a prime number
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<math.h> // Write a function to determine whether a number is a prime //is_prime(i) // return 1 It means a prime number // return 0 It means that it is not a prime number int is_prime(int n) { //2~n~1 Try to remove //2~sqrt(n) Try to remove int j = 0; for (j = 2; j <= sqrt(n); j++) { if (n % j == 0) { return 0; } } return 1; } int main() { // Print 100~200 The prime between int i = 0; for (i = 100; i <= 200; i++) { // Judge i Prime or not if (is_prime(i) == 1) { printf("%d ",i); } } }
Write a function to determine whether a year is a leap year
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> // Write a function to determine whether a year is a leap year int is_leap_year(int y) { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) return 1; else return 0; } int main() { //1000~2000 The leap year of the year int y = 0; for (y = 1000; y <= 2000; y++) { // Judge y Is it a leap year if (is_leap_year(y) == 1) { printf("%d ", y); } } return 0; }Can this code be simplified ?
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> // Write a function to determine whether a year is a leap year //int is_leap_year(int y) //{ // if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) // return 1; // else // return 0; //} int is_leap_year(int y) { return ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0); } int main() { //1000~2000 The leap year of the year int y = 0; for (y = 1000; y <= 2000; y++) { // Judge y Is it a leap year if (is_leap_year(y) == 1) { printf("%d ", y); } } return 0; }
Write a function , To realize binary search of an ordered array
// Write a function , To realize binary search of an ordered array // Find it and return the subscript // No return found -1 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;// Can't find } int main() { // // When passing parameters to an array , Passing is not the whole array // Passing is the address of the first element of the array // int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; int k = 0; scanf("%d", &k);// The element to look for int sz = sizeof(arr) / sizeof(arr[0]); int ret = binary_search(arr, k, sz); if (-1 == ret) printf(" Can't find \n"); else printf(" eureka , The subscript is :%d\n", ret); return 0; }
Write a function , Every time you call this function , Will be num The value of the increase 1
// Write a function , Every time you call this function , Will be num The value of the increase 1 void test(int* p) { //*p = *p + 1; (*p)++; } int main() { int num = 0; test(&num); printf("%d\n", num); return 0; }
5. Nested calls and chained access to functions
Functions and functions can be combined according to actual needs , That is, calling each other
( In a nutshell A You can call B,B You can call A)
5.1 Nested calls
#include <stdio.h>
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; }5.2 Chained access
Take the return value of one function as the parameter of another function .
#include <stdio.h>
#include <string.h>
int main()
{
char arr[20] = "hello";
int ret = strlen(strcat(arr,"bit"));// Here is an introduction strlen function
printf("%d\n", ret);
return 0; }
#include <stdio.h>
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; }To some , Little bit ~
Remember one button three times ! Three even !! Three even !!!

边栏推荐
- How can Plato obtain premium income through elephant swap in a bear market?
- My problem solving record 1: the @component annotation is used on the class. If you want to use the methods in this class, you can't directly new, but should use @autowired for injection, otherwise an
- 怎么样的框架对于开发者是友好的?
- node(二)
- 深入浅出依赖注入及其在抖音直播中的应用
- PyQt5快速开发与实战 6.5 QGridLayout(网格布局)
- PyQt5快速开发与实战 6.4 QBoxLayout(框布局)
- [Apple Developer account]06 after transferring the developer account, the annual fee of the developer is automatically renewed
- Linear regression of machine learning (least square handwriting +sklearn Implementation)
- Fluent text editor
猜你喜欢
![[C language] minesweeping (recursive expansion + marking function)](/img/f6/835ac4ba6588fa61edb30446f4c708.png)
[C language] minesweeping (recursive expansion + marking function)

Network security (6)

How to realize the isolation level between MySQL transactions and mvcc

Explanation of C value type and reference type

PyQt5快速开发与实战 6.1 好软件的三个维度 && 6.2 PyQt5中的布局管理 && 6.3 PyQt5的绝对位置布局

Intel joins hands with datawhale to launch learning projects!

Random number setting and reference between parameters

Behind 100000 visits...

C# 值类型和引用类型讲解

Window系统操作技巧汇总
随机推荐
Div horizontal layout aligned on both sides
How to introduce your project experience?
【微信小程序】接口生成自定义首页二维码
Fluent text editor
Node (II)
Sed, regular expression of shell programming
Pytest+allure generate test report
There is still a chance
读博后降维打击数学建模!
View port occupancy
Linear regression of machine learning (least square handwriting +sklearn Implementation)
i.MX6ULL驱动开发 | 32 - 手动编写一个虚拟网卡设备
Functions and arrays
这是一份不完整的数据竞赛年鉴!
How to query express logistics and filter out no information doc No. to delete or copy
详解:到底什么是GPS北斗授时服务器?
尹伊:我的学习成长路径
Senparc.Weixin.Sample.MP源码剖析
SiC Power Semiconductor Industry Summit Forum successfully held
Anfulai embedded weekly report no. 273: 2022.07.04--2022.07.10







