[C Language Elementary] The specific usage of the function, this blog is enough

insert image description here

Junxi_'s personal homepage

Be diligent and encourage the years to wait for no one

C/C++ game development


Hello, this is Junxi_, and today I am here to update you with the content in the 0-basic C language! What I bring to you today is the call and use of functions in the C language. Let's start directly without talking nonsense!

1. What is a function?

  • Wikipedia's definition of function: subroutine.

  • In computer science, a subroutine is a certain part of 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. Generally, there will be input parameters and a return value, providing the encapsulation of the process and the hiding of details. These codes are usually integrated as software libraries

2. Commonly used functions

1. Library functions

What will have library functions?

1. We know that when we are learning C language programming, we are always impatient to know the result after a code is written, and want to print the result to our screen for viewing. At this time, we will frequently use a function: print information to the screen in a certain format (printf).
2. In the process of programming, we will frequently do some string copy work (strcpy).
3. In programming, we also calculate, and always calculate the operation (pow) of n to the kth power.

  • Like the basic functions we described above, they are not business codes. Every programmer in our development process may use it,

  • In order to support portability and improve program efficiency, a series of similar library functions are provided in the basic library of C language, which is convenient for programmers to develop software.

  • Many beginners may have doubts about the following code, what is it?

#include <stdio.h>
  • 这就是我们使用的最基本的一个包含库函数的头文件,你所用的scanf,printf等都定义在它里面。

  • Do not believe? let's verify
    insert image description here

  • It can be seen that without library functions, our program cannot run.

  • So how to learn library functions?

  • Here is a website for learning library functions: c plus plus
    insert image description here

  • To briefly summarize, the library functions commonly used in C language are:

IO functions
String manipulation functions
Character manipulation functions
Memory manipulation functions
Time/date functions
Mathematical functions
Other library functions

  • Note:
    A secret that library functions must know is: to use library functions, the header files corresponding to #include must be included.

How to learn to use library functions?

  • Need to memorize them all? no!

  • Need to learn how to use query tools:
    MSDN (Microsoft Developer Network)
    c plus plus
    English
    version Chinese version

  • 英文很重要。最起码得看懂文献。

  • So if you want to really learn C language well, you must pay attention to improving your English level!

2. Custom functions

If library functions can do everything, what do we programmers do?
So more important 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 room to play

The composition of the function:

ret_type fun_name(para1, * )
{
    
    
statement;//语句项
}
ret_type 返回类型
fun_name 函数名
para1   函数参数
  • Let us now give you a few practical examples to show you

Write a function to find the largest 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;
}
  • Let the code go to see our effect
    insert image description here
  • Another example:

Write a function that swaps the contents of two integer variables.

void Swap2(int* px, int* py)
{
    
    
	int tmp = 0;
	tmp = *px;
	*px = *py;
	*py = tmp;
}
int main()
{
    
    
	int num1 = 1;
	int num2 = 2;
	
	Swap2(&num1, &num2);
	printf("Swap2::num1 = %d num2 = %d\n", num1, num2);
	return 0;
}

  • The result is as follows:
    insert image description here

  • The first code is very simple and I won’t talk about it here, and the second code will be introduced as an example in the call by value and call by address of the following functions. If you don’t understand it here, don’t worry about it.

  • Someone here might ask:

  • Why define a function, can't I just type it in the main program?

The meaning of defining and encapsulating functions:

insert image description here

function parameters

  • Actual parameters (actual parameters):
    The parameters that are actually passed to the function are called actual parameters.
    Actual parameters can be: constants, variables, expressions, functions, etc.
    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.
  • Formal parameters (formal parameters):
    Formal parameters refer to 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.
  • Compare this code with the above implementation to exchange two integer variable function swap2
//实现成函数,但是不能完成任务
void Swap1(int x, int y)
{
    
    
	int tmp = 0;
	tmp = x;
	x = y;
	y = tmp;
}
int main()
{
    
    
	int num1 = 1;
	int num2 = 2;
	Swap1(num1, num2);
	printf("Swap1::num1 = %d num2 = %d\n", num1, num2);
	return 0;
}
  • operation result:
    insert image description here
  • The parameters x, y, px, py in the above Swap1 and Swap2 functions are all formal parameters.
  • The num1 and num2 passed to Swap1 in the main function and the &num1 and &num2 passed to the Swap2 function are the actual parameters.
  • Since the formal parameter is destroyed directly after being used in the function, it will not be printed in our main function at all, so the exchange of num1 and num2 has not been realized.
  • Notice
  • When the Swap1 function is called, x and y will have their own space and have exactly the same content as the actual parameters.
    So we can simply think that: After the formal parameter is instantiated, it is actually equivalent to a temporary copy of the actual parameter.

3. Function call

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

2. Call by address

  • 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.

  • 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 .

  • 有关传值调用与传址调用相关的小练习:

  • function to print prime numbers

//写一个函数判断是不是素数
//并把1-200之间的结果打印出来
#include<math.h>
int is_prime(int i)
{
    
    
	int j = 0;
	
	
		for (j = 2; j <=sqrt(i); j++)//sqrt为平方根
		{
    
    
			if (i % j == 0)
			{
    
    
				
				return 0;
				
			}
		}
		return 1;
		
	
}
int main()
{
    
    
	int i = 0;
	int count = 0;
	
	for (i = 101; i < 201; i += 2)
	{
    
    
		int ret = is_prime(i);
		if(ret == 1)
		{
    
    
			printf("%d ", i);

			count++;
		}
	}
	printf("\n 一共%d个素数", count);

}

insert image description here

  • binary search function
用函数的形式实现二分法查找
int Find(int arr[], int k, int sz)
{
    
    
	int left = 0;
	int right = sz - 1;
	
	while (left <= right)
	{
    
    
		//int mid = (left + right) / 2;
      int mid=left+(right-left)/2;//防止栈溢出
		if (arr[mid] == k)
		{
    
    
			return mid;
			break;
		}
		else if(arr[mid]<k)
		{
    
    
			left = mid + 1;
		}
		else {
    
    
			right = mid - 1;
		}
		
	}
	  return 1;
}
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int k = 7;
	int sz = sizeof(arr) / sizeof(arr[0]);
	int ret=Find(arr, k, sz);
	if (ret == 1)
	{
    
    
		printf("找不到\n");
	}
	else
		printf("找到了,下标是%d", ret);
	return 0;
}


Four. Function nested call and chain access

Functions and functions can be combined according to actual needs, that is, they call each other.

1. Nested calls

  • Functions can be called nestedly, but definitions cannot be nested.
  • The sample code is as follows:

#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;
}

insert image description here

  • Nested definitions. The following code doesn't even compile.

#include<stdio.h>
void new_line()
{
    
    
    printf("hehe\n");
    void three_line()
    {
    
    
        int i = 0;
        for (i = 0; i < 3; i++)
        {
    
    
            printf("%d ", i);
        }
    }
}

int main()
{
    
    
    three_line();
    return 0;
}

insert image description here

2. Chain access

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

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

insert image description here

  • The return value of the printf function is the number of characters printed on the screen
  • The first printf prints "43"
    - the second printf prints the number of characters on the screen at this time, which is "2"
  • The third printf prints the number of characters "1" in the same way
  • This is why the above code results in

6. Function declaration and definition

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.

2. Function definition:

  • The definition of a function refers to the specific realization of the function, explaining the function realization of the function.
  • The content of test.h
    places the declaration of the function
//函数的声明
int Add(int x, int y);
  • Implementation of the content placement function of test.c
#include "test.h"
//函数Add的实现
int Add(int x, int y)
{
    
    
return x+y;
}

Summarize

  • The above is all the content of today, the basic usage of the function and what should be involved in the call should be involved.
  • If you have any questions, please point them out in the comment area or private message me, I will reply as soon as I see it!

It is not easy for a new blogger to create. If you feel that the content of the article is helpful to you, you may wish to click on this new blogger before leaving. Your support is my motivation to update! ! !

(Ke Li asks you to support the blogger three times in a row!!! Click the comment below to like and collect to help Ke Li)
insert image description here

Guess you like

Origin blog.csdn.net/syf666250/article/details/131328367