C++ function parameters and return values

PHPz
Release: 2024-04-12 17:48:02
Original
826 people have browsed it

Functions in C pass data through parameters and return information through return values: Parameters: Declared in the function definition, allowing the function to receive external values. Return value: Declared in a function definition that enables the function to return information to the calling code.

C++ 函数的参数和返回值

Parameters and return values of C functions

Functions play a vital role in C. They allow us to organize code into reusable modules and facilitates communication between code blocks by passing parameters and return information.

Parameters

Function parameters allow us to provide values to functions that can be used inside the function. The parameters are declared in the function definition as follows:

int sum(int a, int b) { return a + b; }
Copy after login
Copy after login

In the above example, thesumfunction hastwo parameters,aandb, these parameters represent the two integers to be added.

Return Value

Return value allows a function to return information to the code that called it. The function declares its return value in the definition as follows:

int sum(int a, int b) { return a + b; }
Copy after login
Copy after login

In the above example, thesumfunction returns anintvalue representing the two input integers of and.

Practical case

Consider a function that calculates the area of a triangle:

double calculate_triangle_area(double base, double height) { return 0.5 * base * height; }
Copy after login

We can call this function by passing the base length and height values as follows:

double base = 5.0; double height = 10.0; double area = calculate_triangle_area(base, height); std::cout << "Triangle area: " << area << std::endl;
Copy after login

In this example, thecalculate_triangle_areafunction returns the area of the triangle, which is stored in theareavariable and printed to the console.

The above is the detailed content of C++ function parameters and return values. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!