C language - basic usage of functions

1. Why use functions?

Functions in C language are divided into self-defined functions and library functions.

Common library functions when learning C language at the beginning include printf, scanf, etc. We need to include header files when using them. ; eg scanf and printf header files are #include <stdio.h>.

We can see that a function solves a class of problems, so when our code uses the same code in multiple places to solve the same problem, we can customize a function to reduce the amount of code .

2. How to customize a function?

For example:

//(函数返回值类型) (函数名) (参数类型 a,参数类型 b,...)
//{
//实现一些功能的代码;
//返回函数; 
//}
int sum(int a,int b)
{
	return a + b;//把a+b的值返回给函数(sum = a + b) 
}

My suggestion is to define the function directly before the main function, for example:

#include <stdio.h>

int sum(int a,int b)
{
	return a + b;//把a+b的值返回给函数(sum = a + b) 
}
int main()
{
	int a,b;
	a = b =1;
	printf("%d",sum(a,b)); 
	return 0;
}

It can also be written like this:

define after declaration

#include <stdio.h>

int sum(int a,int b);

int main()
{
	int a,b;
	a = b =1;
	printf("%d",sum(a,b)); 
	return 0;
}
int sum(int a,int b)
{
	return a + b;
}

Regarding the parameters (formal parameters) of functions, it is recommended to learn more about pointers before learning more about them. Now you need to know that to pass parameters to the function and then change the parameters, you need to pass the address.

Guess you like

Origin blog.csdn.net/m0_74358683/article/details/130454246