Home > Backend Development > C++ > C++ function declarations and definitions

C++ function declarations and definitions

王林
Release: 2024-04-11 13:27:02
Original
887 people have browsed it

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.

C++ 函数的声明和定义

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, ...);
Copy after login
  • 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;
}
Copy after login
  • Function definition includes everything in the function declaration, as well as the function body.
  • The function body contains the code to be executed.
  • 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);
Copy after login

Definition:

int sum(int num1, int num2) {
    return num1 + num2;
}
Copy after login

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;
Copy after login

Output:

和为: 30
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template