Sunday, January 1, 2012

Return Statement


Return Statement
The keyword return is used to terminate function and return a value to its caller. The return statement may also be used to exit a function without returning a value. The return statement may or may not include an expression.
     The general syntax of the return statement is,
                     return;
                     return (expression );
     The return is a full-fledged C++ statement that can appear anywhere within a function body. A function can also have more then one return although it is good programming style for a function to have a single entrance and a single exit.
    Following are some valid return statement:
           return;
         return  (54) ;
           return  (x+y) ;
         return  (++i) ;
         return  ++j ;      /* correct , but not good style */
   The return statement terminates the execution of the function and pass on the control back to the calling environment.
    For example, a few valid function declarations are,
    (1)
          int sum (int x, int y)
        {
               Return (x+y) ;    / / return int value
        }
    (2)
           float maximum (float a, float b)
         {
              if ( a > b)
                   return (a) ;
              else
                   return (b) ;
         }   / / return floating point value
PROGRAM
A program to find the maximum of any three numbers using multiple return statement in a function definition.
/ /  using multiple return statements in a function
#include <iostream.h>
void main (void)
{
    float maximum (float, float, float) ;
    float x, y, z, max;
    cout << “ enter three numbers \n” ;
    cin >> x >> y >> z ;
    max = maximum (x, y, z) ;
    cout << “ maximum = “ << max;
}
float maximum (float a, float b, float c)
{
    if  (a > b)  {
         if  (a > c)
              return (a) ;
         else
              return (c) ;
    }
    else  {
            if (b > c)
                return (b) ;
           else
                return (c) ;
     }
}  / / end of function
Output of the above program
    enter three numbers
    4    5   6
    maximum = 6 

No comments:

Post a Comment