C++ Return values from functions
The data types that C++ functions can return values of include int, double, char, bool, struct, pointer, etc. The function signature, which is the line that begins with the keyword “type” followed by the function name and the parameters in parentheses, declares the return type of a function.
Syntax:
type function_name(parameters) {
// function body
return value;
}
The value that the function returns in this case is the “type,” or data type. The function’s name is “function name,” and the arguments provided to the function are “parameters.” The function’s output is returned to the calling code using the “return” statement.
Example:
int add(int a, int b) {
int sum = a + b;
return sum;
}
This function takes two integer arguments “a” and “b”, adds them together, and returns the result as an integer value.
int main() {
int num1 = 5, num2 = 10, sum;
sum = add(num1, num2);
cout << "The sum is: " << sum << endl;
return 0;
}
Here, we call the “add” function while declaring the two integer variables “num1” and “num2” and supplying them as arguments. The main function’s “sum” variable is then set to the result of the “add” function’s computation of the two numbers’ sum. The value of “sum” is then printed to the console.
This allows us to reuse code and create more modular programmes by using the return statement to transfer values from a function back to the caller code.