Home >Backend Development >C++ >C++ function declarations and definitions
Function declaration and definition are necessary in C. The function declaration specifies the return type, name and parameters of the function, while the function definition contains the function body and implementation. First declare the function and then use it in your program passing the required parameters. Use the return statement to return a value from a function.
Declaration and Definition of C Functions
In C, a function is a block of code that performs a specific task and returns the required value. To use a function, you must declare it before you can reference it in your program. The following is the syntax for function declaration and definition:
Function declaration:
returnType functionName(parameter1Type parameter1Name, ...);
returnType
: The data type returned by the function. functionName
: The name of the function. parameterList
: The type and name of the parameters required by the function. Function definition:
returnType functionName(parameter1Type parameter1Name, ...) { // 函数体 return value; }
return
statement is used to return a value from a function. Practical case:
Let us create a function to calculate the sum of two numbers.
Declaration:
int sum(int num1, int num2);
Definition:
int sum(int num1, int num2) { return num1 + num2; }
Usage:
In the main()
function, we can call the sum()
function using the following code:
int num1 = 10; int num2 = 20; int result = sum(num1, num2); cout << "和为: " << result << endl;
Output:
和为: 30
The above is the detailed content of C++ function declarations and definitions. For more information, please follow other related articles on the PHP Chinese website!