• Home
  • 6.6 Return Values

6.6 Return Values

View Categories

6.6 Return Values

1 min read

Table of Contents

A function can return a value to the code that called it. The return type specified in the function declaration or definition determines the type of value that the function can return.

The return statement terminates the execution of the current function and optionally provides a value to the caller. The returned value can be stored in a variable, used directly in an expression, or passed to another function.

Source Code #

#include <iostream>

int multiply(int first, int second)
{
    return first * second;
}

int main()
{
    int result = multiply(6, 7);

    std::cout << "Result: " << result << '\n';

    return 0;
}

Output #

Result: 42

Explanation #

  • int multiply(int first, int second) defines a function that returns an int value.
  • return first * second; calculates the product and returns the resulting value to the caller.
  • The return statement terminates the execution of multiply().
  • multiply(6, 7) calls the function with 6 and 7 as arguments.
  • The value returned by multiply() is assigned to the variable result.
  • A returned value can be used directly in an expression instead of being stored in a variable.
  • The type of the returned expression must be compatible with the function’s declared return type.
  • A function whose return type is not void must return a value through an appropriate return statement.
  • return 0; in main() terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *