Course Content
C++ Functions
C++ Functions
Returning Values With Simple Data Types
In C++, functions can return values of simple data types such as integers, floating-point numbers, and characters. To specify the return type of a function, you indicate the data type before the function name in the function signature.
When the function is executed, it can compute a value, which is then returned using the return
statement. This type of return value was used in the code examples before:
main
#include <iostream> // Function that adds two integers and returns the result int addNumbers(const int a, const int b) { int sum = a + b; return sum; } int main() { int num1 = 3; int num2 = 5; // Call the function and store the returned result in a variable int result = addNumbers(num1, num2); // Print the result std::cout << "The sum of " << num1 << " and " << num2 << " is: " << result << std::endl; }
The addNumbers()
function is declared to return an integer value by using the int
specifier before the function name. It calculates the sum of a
and b
and returns the result as an int
.
Note
Ensure that the variable where you intend to store the returned value inside the
main()
block matches the data type of the corresponding return value.
Please note that the function's return value can be specified only within the function signature. Even if you try to return a value of a different type using the return
statement, it will be automatically cast to the data type declared in the function signature:
main
#include <iostream> // Function that adds two integers and returns the result int addNumbers(const double a, const double b) { double sum = a + b; return sum; } int main() { double num1 = 3.5; double num2 = 5.1; // Call the function and store the returned result in a variable int result = addNumbers(num1, num2); // Print the result std::cout << "The sum of " << num1 << " and " << num2 << " is: " << result << std::endl; }
We observe that the sum calculated within the function is of double
type, but the function's return type is declared as int
. Consequently, the final return value was explicitly converted to an int data type, resulting in 8
instead of 8.6
.
Note
Note that we can return only one value from a function using a simple datatype specifier. To return multiple values, we should use arrays or custom structures (classes).
Thanks for your feedback!