Nested calls of C language functions

The function definitions in C language are parallel and independent to each other. That is to say, when defining a function, another function cannot be defined within a function, that is, nested definitions cannot be nested, but functions can be nested, that is, when calling a function In the process, another function is called.
As shown in the figure below: it represents two layers of nesting (a total of three layers of functions including main).
Please add a picture description
During its execution process:
① Execute the beginning of the main function
② Encounter a function call statement, call function a, the process transfers to function a ③
Execute the beginning of function a
④ Encounter a function call statement, call function b, the process transfers to function a b
⑤Execute function b, if there are no other nested functions, complete all operations of function b
⑥Return to the position where function b is called in function
a ⑦Continue to execute the unexecuted part of function a until the end of function a
⑧Return The position where function a is called in the main function
⑨Continue to execute the rest of the main function until the end
[Example]
Input 4 integers and find the largest number among them. Handled with nested calls of functions.
[Thoughts]
Define the function Max4, which is used to realize the function of finding the largest of the 4 numbers. Define the Max2 function, which is used to find the larger of two numbers. Call the Max4 function in the main function, and then call another function Max2 in Max4. In Max4, by calling the Max2 function multiple times, you can find the larger of the 4 numbers, and then return it to the main function as the function value, and output the result in the main function.
【Code】

int Max2(int x,int y)
{
    
    
	return(x>y?x:y);
}
int Max4(int w,int x,int y,int z)//定义Max4函数
{
    
    
	int Max2(int x,int y);//对Max2的函数声明
	int m;
	m=Max2(w,x);//调用Max2函数,得到w,x两个数中的大数放在m中
	m=Max2(m,y);//调用Max2函数,得到w,x,y三个数中的大数放在m中
	m=Max2(m,z);//调用Max2函数,得到w,x,y,z四个数中的大数放在m中
	return m;//把m作为函数值带回main函数
}
int main()
{
    
    
	int a,b,c,d;
	printf("从键盘输入4个整数:\n");//提示输入4个数
	scanf("%d%d%d%d",&a,&b,&c,&d);//输入4个数
	int m;
	m=Max4(a,b,c,d);//调用Max4函数,得到4个数中最大者
	printf("4个数中最大的数为:%d",m);//输出4个数中最大者
	return 0;
}

【result】
Please add a picture description

Guess you like

Origin blog.csdn.net/NuYoaH502329/article/details/127863866