Mark As Completed Discussion

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 add that takes two integers a and b as parameters.
  • Inside the function, we use the return statement to specify the sum of a and b as the return value.
  • In the main function, we call the add function with the arguments num1 and num2, and we store the returned value in the variable sum.
  • Finally, we use cout to display the sum of num1 and num2.

When you run the code, the output will be:

SNIPPET
1The sum of 10 and 20 is: 30
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment