The difference between custom function before and after main function in C language

 

The C language requires functions to be defined first and then called, and the calling function is placed after the called function, just like the variable is defined first and then used. If the calling function is placed before the custom function, you need to add the function prototype declaration before the function call . If it is not declared, the function to be called will be of type int by default at compile time .

The date of the function declaration is mainly to explain the type of the function and the status of the parameters, so as to ensure that the program can judge whether the call to the function is correct and perform the corresponding compilation processing when the program is compiled.

 

Examples of correct code:

The custom function is before the main function:

#include <stdio.h>


void Swap(int *X, int *Y)
{
	/*交换数值*/
	int tmp;
	tmp = *X; *X = *Y; *Y = tmp;
}


int main()
{
	int X = 10, Y = 20;

	Swap(&X, &Y);
		
	printf("X=%d, Y=%d\n", X, Y);

	return 0;
}

The custom function is after the main function:

#include <stdio.h>


int main()
{
	int X = 10, Y = 20;

	void Swap(); /*主调函数放在自定义函数的前面,需要在函数调用前,加上函数原型声明*/
	Swap(&X, &Y);
		
	printf("X=%d, Y=%d\n", X, Y);

	return 0;
}


void Swap(int *X, int *Y)
{
	/*交换数值*/
	int tmp;
	tmp = *X; *X = *Y; *Y = tmp;
}

 

Guess you like

Origin blog.csdn.net/Dust_Evc/article/details/113782410