当前位置:网站首页>C language explanation series - understanding of functions (4) declaration and definition of functions, simple exercises
C language explanation series - understanding of functions (4) declaration and definition of functions, simple exercises
2022-07-26 05:22:00 【Sad pig, little pig】
List of articles
Function declaration and definition
Declaration of functions
The declaration concept and function of function are as follows
1. The declaration of a function is to tell the compiler what a function is called , What are the parameters , What is the return value type . But does it exist , Function declarations do not solve
2. Function declarations usually appear before the use of functions . To satisfy the requirement of declaration before use .
3. The declaration of functions is usually in the header file .
We demonstrate the specific usage of function declaration in the code
int main()
{
int num1 = 20;
int num2 = 10;
int max = get_max(num1, num2);
printf("%d", max);
return 0;
}
int get_max(int x, int y)
{
return(x > y ? x : y);
}
Or the code that uses the function to solve the maximum value of two numbers , This time we put the custom function after the main function , Let's make the code run
Although we can also get our results, the compiler will have a warning
He said ours “get_max" Undefined , Here we need to use the function declaration to eliminate this warning .
When our custom function is after the main function , When we want to call a custom function , You need to use the declaration of the function , Tell the compiler that there is such a function before calling , This is it. : Function declarations usually appear before the use of functions , To satisfy the requirement of declaration before use .
Definition of function
As the name suggests, the definition of function is The concrete realization of function , The function realization of the replacement function . When we understand the function declaration and definition , So how should we write the declaration and definition of functions in our daily work ? In daily work, you must not declare functions like the above code , The declaration and definition of functions must be separate . for example
We can see that there is no definition in this source file get_max() This function , There is no function declaration , But we can still get the results we want by executing the code. Why ? as a result of , We divide the declaration and definition of functions into two parts , Write in different places
The advantage of writing like this is , Our requirements can be divided into multiple modules for writing , Finally, we can achieve the desired effect by combining them , In this regard, we will share with you in detail in the future study , Today, you only need to know what is the declaration and definition of a function .
Simple exercises
After our sharing , I believe you also have a certain understanding of functions , Today we will lead you to practice several topics , Let's review our previous knowledge .
Write a function to determine whether a number is a prime
We also wrote such a topic in the previous exercise , So how to use function implementation ?
int prime_number(int x)
{
int j = 0;
for (j = 2; j < x; j++)
{
if (x % j == 0)
{
return 0;
}
}
if (j == x)
{
return 1;
}
}
int main()
{
int num = 0;
printf(" Enter a number :");
scanf("%d", &num);
int i = prime_number(num);
if (1 == i)
{
printf("%d Prime number ", num);
}
else
{
printf("%d Not primes ",num);
}
}
Thought analysis : First, we create a variable to receive the number of pending judgments we enter , Pass this number to the custom function , Judge if the return value is 1 So it's a prime number , The user-defined function implements the judgment part , If it is a prime, it returns 1, Not just back 0.
Write a function to realize binary search
// Use function to realize binary search of shaping ordered array
int binary_search(int arr[])
{
int left = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
int right = sz - 1;
int k = 0;
printf(" Please enter the array element to query :");
scanf("%d", &k);
while (left <= right)
{
int mid = (right - left) / 2 + left;
if (k > arr[mid])
{
left = mid + 1;
}
else if (k < arr[mid])
{
right = mid - 1;
}
else
{
return mid;
}
}
if (left > right)
{
return -1;
}
}
int main()
{
int arr[10] = {
1,2,3,4,5,6,7,8,9,10 };
int num = binary_search(arr);
if (num == -1)
{
printf(" Can not find ");
}
else
{
printf(" eureka , Subscript to be %d", num);
}
return 0;
}
Thought analysis : Let's first create an integer ordered array , Pass the array to the custom function to find , If it can be found, the array subscript of the value to be checked is returned , If you can't get it back -1, Select the output through the return value , Give the corresponding prompt to the user . After writing, we execute our code
We found that , When looking for elements that exist in the array , Hint that we can't find , Where is the problem ? We look for the answer in debugging
We found it was ours right There is an error in the value of , There is clearly 10 Elements ,right It should be equal to 9, Why become 1 What about it ? The answer is , Array will not pass the whole array when passing parameters , Just pass the address of the first element of the array to find any element in the array , So when passing parameters in an array, you can not only use the above int binary_search(int arr[]) This way of writing , It can also be written as int binary_search(int *arr), The latter is more difficult to understand , But it reveals the essence , The array passing parameter is actually the passing of the first element of the array . So we will change our code :
// Use function to realize binary search of shaping ordered array
int binary_search(int arr[], int sz)
{
int left = 0;
int right = sz - 1;
int k = 0;
printf(" Please enter the array element to query :");
scanf("%d", &k);
while (left <= right)
{
int mid = (right - left) / 2 + left;
if (k > arr[mid])
{
left = mid + 1;
}
else if (k < arr[mid])
{
right = mid - 1;
}
else
{
return mid;
}
}
if (left > right)
{
return -1;
}
}
int main()
{
int arr[10] = {
1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
int num = binary_search(arr, sz);
if (num == -1)
{
printf(" Can not find ");
}
else
{
printf(" eureka , Subscript to be %d", num);
}
return 0;
}
We will right() The value of this variable is found in the main function , Then pass it to the user-defined function to realize our requirements .
Write a function , Every time you call this function , Will be num The value of the increase 1.
Through the title, we know , You need to define a function to make the value of the number in the main function +1, In this way, a certain connection needs to be established inside and outside the function , We use Address call .
#include<stdio.h>
void add(int* pnum)
{
*pnum = *pnum + 1;
}
int main()
{
int num = 0;
add(&num);
printf("%d", num);
return 0;
}
边栏推荐
- 如何从内存解析的角度理解“数组名实质是一个地址”?
- LNMP架构
- Recommended reading: how can testers get familiar with new businesses quickly?
- OD-Paper【1】:Rich feature hierarchies for accurate object detection and semantic segmentation
- 提升命令行效率的 Bash 快捷键 [完整版]
- Okaleido上线聚变Mining模式,OKA通证当下产出的唯一方式
- Migrate the server and reconfigure the database (the database has no monitoring, and the monitoring starts with tns-12545, tns-12560, tns-00515 errors)
- An online accident, I suddenly realized the essence of asynchrony
- 家居vr全景展示制作提高客户转化
- Week 6 Learning Representation: Word Embedding (symbolic →numeric)
猜你喜欢

Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output

Trend of the times - the rise of cloud native databases

Shell流程控制(重点)、if 判断、case 语句、let用法、for 循环中有for (( 初始值;循环控制条件;变量变化 ))和for 变量 in 值 1 值 2 值 3… 、while 循环

FTP实验及概述

第二讲 初识SLAM

Lesson 2 getting to know slam for the first time

Common modules in ansible

The first positive number missing in question 41 of C language. Two methods, preprocessing, fast sorting and in situ hashing

Embedded sharing collection 21

Recommend 12 academic websites for free literature search, and suggest to like and collect!
随机推荐
JVM Lecture 6: how to solve the frequent FGC in online environment?
List converted to tree real use of the project
Mathematical modeling and optimization analysis based on general optimization software gams
测试必备工具之Fiddler,你真的了解吗?
CMD operation command
ALV report flow diagram
家居vr全景展示制作提高客户转化
C语言函数
Use playbook in ansible
pillow的原因ImportError: cannot import name ‘PILLOW_VERSION‘ from ‘PIL‘,如何安装pillow<7.0.0
LNMP架构
STL常用模板库
C language force buckle question 42 of rain. Four methods - violence, dynamic planning, stack, double pointer
nn.Moudle模块-创建神经网络结构需要注意的细节
Excel vba: saving multiple worksheets as new files
flex布局原理及常见的父项元素
When AQS wakes up the thread, I understand why it traverses from the back to the front
Do you really understand fiddler, a necessary tool for testing?
Go exceed API source code reading (VI) -- deletesheet (sheet string)
推荐必读:测试人员如何快速熟悉新业务?