Home >Backend Development >C++ >The purpose of function return value in C++
In C, a function can return a value through the return keyword, which can be any data type, including numeric values and objects. The return value is used to pass information or calculation results to the caller, and can be used to check errors, optimize performance, and implement the single responsibility principle.
In C, a function can return a value through the return
keyword. Return values can be used to pass calculation results or information to the caller.
The function return value can be any data type, including Boolean values, characters, integers, floating point numbers, and custom objects.
The syntax of function return value is as follows:
<return_type> function_name(...) { // 函数体 return value; }
Where:
3081bc6c542a4be2b6e2eca3709ff4f5
is a function The type returned. function_name
is the name of the function. (...)
is the parameter list of the function (optional). value
is the value returned by the function. Consider the following function that calculates area:
double calculate_area(double base, double height) { return base * height / 2; }
This function has two double-precision floating point parameters: base
and height
. It returns half the product of these two arguments.
In the main
function, we can use this function to calculate the area of the triangle:
int main() { double base = 5.0; double height = 10.0; double area = calculate_area(base, height); cout << "三角形的面积为:" << area << endl; return 0; }
The output is as follows:
三角形的面积为:25
In addition to passing calculation results, function return values can also be used for:
The above is the detailed content of The purpose of function return value in C++. For more information, please follow other related articles on the PHP Chinese website!