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.
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.
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 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.
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!