Return Values
In C++, a function can also return a value. The return value of a function is specified in the function's definition, and it represents the result of the function's computation.
To specify a return value, you need to declare the return type of the function. The return type can be any valid C++ data type, such as int, float, char, bool, or even a user-defined type.
Let's take a look at an example:
TEXT/X-C++SRC
1#include <iostream>
2
3using namespace std;
4
5int add(int a, int b) {
6 return a + b;
7}
8
9int main() {
10 int num1 = 10;
11 int num2 = 20;
12 int sum = add(num1, num2);
13
14 cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << endl;
15
16 return 0;
17}In this example:
- We have a function named
addthat takes two integersaandbas parameters. - Inside the function, we use the
returnstatement to specify the sum ofaandbas the return value. - In the
mainfunction, we call theaddfunction with the argumentsnum1andnum2, and we store the returned value in the variablesum. - Finally, we use
coutto display the sum ofnum1andnum2.
When you run the code, the output will be:
SNIPPET
1The sum of 10 and 20 is: 30xxxxxxxxxx17
using namespace std;int add(int a, int b) { return a + b;}int main() { int num1 = 10; int num2 = 20; int sum = add(num1, num2); cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << endl; return 0;}OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


