How to call a custom function in C language?
To invoke a custom function, follow these steps:
- Function declaration: Before calling a custom function in the program, it is necessary to declare the function. The function declaration includes the return type, function name, and parameter types.
- Function definition: Specifying the concrete implementation of a function at a certain place in the program. A function definition includes the return type, function name, types of parameters, and function body.
- Function call: Invoking a function at a specific location in a program. It involves using the function name and its parameters.
Below is a sample code demonstrating how to call a custom function.
#include <stdio.h>
// 函数的声明
int add(int num1, int num2);
int main() {
int result;
// 函数的调用
result = add(5, 3);
printf("The sum is %d\n", result);
return 0;
}
// 函数的定义
int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
}
In the example code above, we first declare a function called “add” at the beginning of the program. This function takes two integer parameters and returns an integer value. We then call the “add” function in the main function and assign its return value to the variable “result”. Finally, we use the printf function to output the result.
It is important to note that the function declaration can be placed at the beginning of the program or before the function is called, but the function definition must come before the function is called. This is because in the function declaration, the compiler only needs to know the return type, function name, and parameter types of the function, without needing to know the specific implementation of the function. However, in the function definition, the compiler needs to know the specific implementation of the function in order to correctly generate executable code.