Home  >  Article  >  Backend Development  >  C++ function parameters and return values

C++ function parameters and return values

PHPz
PHPzOriginal
2024-04-12 17:48:02835browse

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;
}

In the above example, the sum function has two parameters, a and b, 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;
}

In the above example, the sum function returns an int value 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;
}

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;

In this example, the calculate_triangle_area function returns the area of ​​the triangle, which is stored in the area variable 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!

Statement:
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