Return values
- C++ course
- Beginner
- Lesson 66/116
- 4 min
Learn to return a value from a function with return.
Returning values with return
A function can send a value back to its caller. The definition int add(int a, int b) { return a + b; } returns the sum to the caller. The return keyword exits the function and gives the value back.
The return type can be any type: int, double, std::string and so on. The void return type means 'returns nothing'; in such functions return may be written without a value or omitted. You can store the returned value or use it directly: int s = add(2, 3);.
void functions
A function does not have to return a value. The void return type marks a function that performs a side effect without computing anything: it prints, writes to a file or changes state.
In void printHello() { std::cout << "hi"; } there is no return. You may write return; (no value) but it is not required; the function ends on its own at the closing brace. You cannot store the call in a variable: int x = printHello(); is a compile error.
Practice Write square and call it
Define an int square(int x) function that returns x*x. In main, call square(6) and print the result with std::cout.
Starter code
#include <iostream>
// Define square here
int main() {
// Print square(6)
return 0;
}Sample solution
#include <iostream>
int square(int x) {
return x * x;
}
int main() {
std::cout << square(6) << std::endl;
return 0;
}Expected output
36
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the return statement
int add(int a, int b) { ____ a + b; }
int add(int a, int b) { return a + b; }
Explanation: return a + b; returns the sum.
2 For int square(int x) { return x*x; } what does square(5) return?
int square(int x) { return x*x; }- 5
- 10
- 25 Correct answer
- 0
Explanation: square(5) calls with x=5, returning 5*5 = 25.
3 Match the return types
| Term | Meaning |
|---|---|
int |
Returns an integer |
double |
Returns a decimal |
void |
Returns nothing |
std::string |
Returns text |