C language learning: 13. Function

What the function does

        If we need to do something repeatedly in the program, such as calculating accumulation, do we need to continuously write accumulation code in the code? The answer is yes when we don't understand the function. Is there an easier way to calm down? Do capitalists have to prepare a new sickle every time they cut leeks? No, as long as you prepare a sickle, you can cut it repeatedly. This sickle is a function, and the sickle is meant to be used repeatedly. The same is true for functions in C language. After it is prepared, it can be used repeatedly.

function type

        Functions can be divided into two categories according to their functions. One is for data processing, such as calculating cumulative sums; the other is for process processing, such as screen printing.

Components of a function

        Function name, function parameters, function return type

返回类型 函数名(参数1, 参数2)
{
    程序语句1;
    程序语句2;
    。。。
    程序语句n;
}


int calculate(int x) //x是输入的参数,int是函数返回的结果
{
    int y = x + 1;

    return y; //返回计算结果y
}

Write and call functions

Program example 1:

#include <stdio.h>

//定义函数
int calculate(int x)
{
	int y = 0;
	y = x + 1;

	return y;
}

int main()
{
	int m1 = calculate(1); //调用函数
	int m2 = calculate(2); //调用函数
	int m3 = calculate(3); //调用函数

	printf("m1 = %d\n",m1);
	printf("m2 = %d\n", m2);
	printf("m3 = %d\n", m3);

	return 0;
}

C language program entry

Guess you like

Origin blog.csdn.net/m0_49968063/article/details/132965878