0
0
C++programming~5 mins

Return values in C++

Choose your learning style9 modes available
Introduction

Return values let a function send back a result after it finishes. This helps you reuse work and get answers from functions.

When you want a function to calculate and give back a number, like adding two numbers.
When you need a function to check something and tell if it is true or false.
When you want to get a string or message from a function after processing.
When you want to break a big task into smaller parts that return results.
When you want to reuse a function's result in different parts of your program.
Syntax
C++
return_type function_name(parameters) {
    // code
    return value;
}

The return_type tells what kind of value the function sends back.

The return keyword sends the value back and ends the function.

Examples
This function adds two integers and returns the sum.
C++
int add(int a, int b) {
    return a + b;
}
This function returns true if the number is even, otherwise false.
C++
bool isEven(int num) {
    return num % 2 == 0;
}
This function returns a greeting message as a string.
C++
std::string greet() {
    return "Hello!";
}
Sample Program

This program shows three functions that return different types: an integer, a boolean, and a string. The main function calls them and prints their returned values.

C++
#include <iostream>
#include <string>

int multiply(int x, int y) {
    return x * y;
}

bool isPositive(int n) {
    return n > 0;
}

std::string getMessage() {
    return "Have a nice day!";
}

int main() {
    int result = multiply(4, 5);
    bool check = isPositive(-3);
    std::string message = getMessage();

    std::cout << "4 * 5 = " << result << "\n";
    std::cout << "Is -3 positive? " << (check ? "Yes" : "No") << "\n";
    std::cout << message << "\n";

    return 0;
}
OutputSuccess
Important Notes

Once a function hits a return statement, it stops running and sends the value back.

If a function has a return type other than void, it must return a value of that type.

Functions with void return type do not return a value.

Summary

Return values let functions send results back to where they were called.

Use return followed by the value you want to send back.

Return types tell what kind of value the function will give.