bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/C++/C++ Functions
C++•C++ Functions

C++ The Return Keyword

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind C++ The Return Keyword?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___(int x) {
3Order

Put the learning moves in the order that makes the concept easiest to apply.

You can also store the result in a variable:
This example returns the sum of a function with two parameters :
The void keyword, used in the previous examples, indicates that the function should not return a value.

Return Values

The void keyword, used in the previous examples, indicates that the function should not return a value. If you want the function to return a value, you can use a data type (such as int , string , etc.) instead of void , and use the return keyword inside the function:

Example

int
myFunction(int x) {
  return 5
  + x;
}
int main() {
  cout << myFunction(3);
  return 0;
}
// Outputs 8 (5 + 3)

This example returns the sum of a function with two parameters :

Example

int myFunction(int x, int y) {
  return x + y;
}
int main() {
  cout << myFunction(5, 3);
  return 0;
}
// Outputs 8 (5 + 3)

You can also store the result in a variable:

Example

int myFunction(int x, int y) {
  return x + y;
}
int main() {
  int z = myFunction(5, 3);
  cout << z;
  return 0;
}
// Outputs 8 (5 + 3)

Pratical Example

Here is a simple and fun "game example" using a function with return to double a number five times:

Example

int doubleGame(int x) {
  return x * 2;
}
int main() {
  for (int i = 1; i <= 5; i++) {
    cout << "Double of " << i << " is " << doubleGame(i) << endl;
  }
return 0;
}

Previous

C++ Multiple Parameters

Next

C++ Pass Array to a Function