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 functionint myfunction(int x) {// declaring the return keyword for the functionreturn 10 + x;}int main() {cout << myfunction(5);return 0;}
Explanation
- Line 5: We create a function,
myfunction(), and pass an integer parameter valuexto the function. - Line 8: We declare the
returnkeyword 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
myfunctionand 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 parametersint myFunction(int x, int y) {// declaring the return keywordreturn x + y;}int main() {cout << myFunction(10, 5);return 0;}
Explanation
- Line 5: We declare the
myfunctionfunction with two parameter values,xandy. - Line 8: We declare the
returnkeyword. - Line 12: We call
myfunctionand pass arguments to the function. The output is printed to the console.