Return

Lesson 15
Author : Afrixi
Last Updated : November, 2022
C++ - Programming Language
This course covers the basics of programming in C++.

The return statement is used to return a value from a function. Here’s an example:

#include <iostream>

int addNumbers(int a, int b);

int main() {
    int x = 5;
    int y = 10;
    int result = addNumbers(x, y);
    
    std::cout << "The sum of " << x << " and " << y << " is " << result << std::endl;
    
    return 0;
}

int addNumbers(int a, int b) {
    int sum = a + b;
    return sum;
}

In this example, the addNumbers function takes two integer parameters a and b, adds them together and stores the result in a variable called sum. The return statement is then used to return the value of sum to the calling function (main in this case).

When the addNumbers function is called from main with arguments x and y, the returned value is assigned to the variable result. Finally, the sum is printed to the console using std::cout.

Functions can also return different types of values, such as double, float, bool, char, and string, among others. Here’s an example of a function that returns a double value:

#include <iostream>

double square(double x);

int main() {
    double y = 5.0;
    double result = square(y);
    
    std::cout << "The square of " << y << " is " << result << std::endl;
    
    return 0;
}

double square(double x) {
    double squared = x * x;
    return squared;
}

In this example, the square function takes a double parameter x, squares it, and returns the result as a double. The function is called from main with an argument of y, and the returned value is assigned to the variable result. Finally, the squared value is printed to the console using std::cout.