C language function declaration needs to give the function name, return value type, parameter list [the focus is on the parameter type] and other information related to the function, the format is [dataType functionName( dataType1 param1, dataType2 param2 ... );].
The C language code is executed from top to bottom. In principle, the function definition must appear before the function call, otherwise an error will be reported. But in actual development, they are often used before the function is defined, and in this case they need to be declared in advance.
The so-called declaration (Declaration) is to tell the compiler that I want to use this function. It doesn’t matter if you don’t find its definition now. Please don’t report an error. I will fill in the definition later.
The format of the function declaration is very simple, which is equivalent to removing the function body in the function definition and adding a semicolon; at the end, as shown below:
dataType functionName( dataType1 param1, dataType2 param2 ... );
You can also write no formal parameters and only write data Type:
dataType functionName( dataType1, dataType2 ... );
The function declaration gives the function name, return value type, parameter list (emphasis on parameter type) and other information related to the function, which is called the function prototype (FunctionPrototype). The function prototype is to tell the compiler information related to the function, so that the compiler knows the existence of the function and its existing form. Even if the function is not defined temporarily, the compiler knows how to use it.
With function declaration, function definition can appear anywhere, even in other files, static link libraries, dynamic link libraries, etc.
[Example 1] Define a function sum(), calculate the sum from m to n, and put the definition of sum() after main().
#include <stdio.h> //函数声明 int sum(int m, int n); //也可以写作int sum(int, int); int main(){ int begin = 5, end = 86; int result = sum(begin, end); printf("The sum from %d to %d is %d\n", begin, end, result); return 0; } //函数定义 int sum(int m, int n){ int i, sum=0; for(i=m; i<=n; i++){ sum+=i; } return sum; }
We called the sum() function in the main() function. Although the compiler did not find the function definition before it, it found the function declaration, so the compiler knew how to use the function. As for the function You don’t have to worry about what the body is for the time being. You can just add the function body later.
Recommended tutorial: "c Language Tutorial"
The above is the detailed content of c language function declaration format. For more information, please follow other related articles on the PHP Chinese website!