Cpp - Function Function Return

Introduction

Functions return a value or void.

To return a value from a function, the keyword return is followed by the value to return.

The value can be a literal, a variable, or an expression, because all expressions produce a value.

Here are some examples of return statement:

return 5; 
return (x > 5); 
return (convert(fahrenheit)); 

These are all permitted return statements.

When a return statement is executed, program execution returns immediately to the statement that called the function.

Any statements following return are not executed.

It is OK to have more than one return statement in a function.

The return statement has the following syntax:

return [expression] 

If the function is any type other than void, the return statement will cause the function to return a value to the function that called it.

If the return type of a function is void, just use

return; 

to exit a function.

When the program flow reaches a return statement or the end of a function code block, it branches back to the function that called it.

If expression is supplied, the value of the expression will be the return value.

The function area() in the following code returns an expression.

Defining and calling the function area(), example for a simple function returning a value.

Demo

#include <iostream> 
#include <iomanip> 
using namespace std; 

double area(double, double);         // Prototype 

int main() //from  ww w  .j a v a 2  s . c  om
{ 
     double  x = 3.5, y = 7.2,  res; 

     res = area( x, y+1);             // Call 

    // To output to two decimal places: 
     cout << fixed << setprecision(2); 
     cout << "\n The area of a rectangle " 
           << "\n with width  " << setw(5)  << x 
           << "\n and length  " << setw(5) << y+1 
           << "\n is          " << setw(5) << res 
           << endl; 
     return 0; 
} 

// Defining the function area(): 
// Computes the area of a rectangle. 
double area( double width, double len) 
{ 
     return (width * len);   // Returns the result. 
}

Result

Related Topics

Exercise