Functions Returning Values

Functions in C++ can not only perform actions but also return values back to the place from where they were called. This is very useful when we want to process or use the result of an operation. The return type of a function must be specified during its definition (e.g., int for integers). To return a value, we use the return keyword. For example:

int add(int a, int b) {
    return a + b;
}

int main() {
    int result = add(3, 4);
    std::cout << result << std::endl; // Prints: 7
    return 0;
}

This add function has a return type of int and two arguments, which it adds and returns using return. We then assign this returned value to the variable result. Note also that the main function returns 0, which indicates successful program termination. Until now, we've omitted this in the main function for simplification, but it's standard practice for the main function to include this.

It's also important to know that returning a value terminates the execution of the function. For example:

std::string rectangleArea(int a, int b) {
    if (a < 0 || b < 0) {
        return "Side lengths cannot be negative!";
    }
    return std::to_string(a * b);
}

int main() {
    std::cout << rectangleArea(3, 4) << std::endl;  // Prints: 12
    std::cout << rectangleArea(-3, 4) << std::endl;  // Prints: Side lengths cannot be negative!
    return 0;
}

This rectangleArea function has a return type of std::string because it returns either a text message or the converted multiplication result as text. When any side is negative, the function returns an error message and the rest of the function is not executed.

Instructions

Complete the subtract function with return type int so that it returns the difference (a-b).

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/7

Functions Returning Values | Start Coder