How to use the return keyword in a function in C++

Overview

In this shot, we want to briefly illustrate how the return keyword is used in a function in C++.

What is the return keyword?

The return keyword in C++ returns a value to a function. The return keyword is declared inside a function to return a value from the given function.

Example

#include <iostream>
using namespace std;
// creating a function
int myfunction(int x) {
// declaring the return keyword for the function
return 10 + x;
}
int main() {
cout << myfunction(5);
return 0;
}

Explanation

  • Line 5: We create a function, myfunction(), and pass an integer parameter value x to the function.
  • Line 8: We declare the return keyword for the function. This tells C++ that the expression right after the keyword should be returned whenever the function is called.
  • Line 12: We call myfunction and pass an argument, 5, to the function. The output is printed to the console.

The return keyword can also be used with two parameters.

Example

#include <iostream>
using namespace std;
// ccreating a function having two parameters
int myFunction(int x, int y) {
// declaring the return keyword
return x + y;
}
int main() {
cout << myFunction(10, 5);
return 0;
}

Explanation

  • Line 5: We declare the myfunction function with two parameter values, x and y.
  • Line 8: We declare the return keyword.
  • Line 12: We call myfunction and pass arguments to the function. The output is printed to the console.

Free Resources