What if your functions could whisper their answers back to you instead of staying silent?
Why Return values in C++? - Purpose & Use Cases
Imagine you are baking cookies and want to share the number of cookies you made with your friend. If you just bake them but don't tell your friend the count, they have no idea how many cookies to expect.
Without return values, you might have to write the cookie count on a piece of paper or shout it out every time. This is slow, easy to forget, and can cause mistakes if the number changes or you bake again.
Return values let a function bake cookies and then hand over the exact number it made directly. This way, the information travels smoothly and can be used immediately without extra steps.
void bakeCookies() {
int count = 12;
// but no way to send count back
}
int main() {
bakeCookies();
// no info about count
}int bakeCookies() {
int count = 12;
return count;
}
int main() {
int cookies = bakeCookies();
// now we know how many cookies
}Return values let functions give back results that other parts of the program can use instantly, making your code smarter and more connected.
When you use a calculator app, it returns the answer after you press equals. That answer is a return value from the calculation function.
Return values send results from functions back to where they were called.
This avoids manual sharing of information and reduces errors.
They make programs more efficient and easier to understand.