Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use | Resource CD
 

Style 3: non-void functionName(void)

Our third style of function takes no arguments, but will return a value.  Up until now, we have been communicating information TO a called function.  Now we will be returning information FROM the function by using the function return value.  The return value can be a constant, a variable, or an expression.  The only requirement is that the return value be of the type specified in the function prototype. 

return_type functionName(void)   //function header
{
     statements;
     return (value);  
 //value is of type return_type
}

Function calls that return values need to have a place in main for the returned value to reside, to be printed, or to be manipulated.  Think of the function as holding out its hand to pass a value back to main.  Main must stretch out its hand (which may be a variable location) for this value to reside.

 Always be sure to do something with a returned value!  Store the return value somewhere; print the return value to the screen; use the return value in a calculation; just use it!!  The following are examples of USES of function return values:

(Function calls with return locations)
x = Avg( i, j)
(Function Avg takes i and j and returns a value stored in x.)

cout<< num(1,3,5); (Function num takes 1, 3 and 5 and its return value is printed)

ans=add(a,b) + add(c,d); (Function add is called twice.  The return values from 2 calls are added and stored in ans.)

//Example program
//Screen display shown at the right
//Returning values from a function

#include<iostream.h>
#include<stdlib.h>

void greeting(int x);   //prototype-no return
int getNumber(void);  //prototype-return integer

int main(void)
{
     system("CLS");
     greeting(5);  //
function call   
     int response;
     response=getNumber( ); //call and
store value
     greeting(response); //
function call
     return 0;
}

//function definition - creates a line of "Hi"s
void greeting(int x)
{
     int i;    
     for(i = 0; i < x; i++)
     {
          cout<<"Hi ";
     }
     cout<<endl;
     return;  
}

//function definition - get the user's # and return it
int getNumber(void)
{
     int number;
     do
     {
          cout<<"Please enter number (1-10)\n";
          cin>>number;
     }
     while((number < 1)||(number > 10));
     return (number);
}

  

 

 

 

 

NOTE:
Functions can return only ONE value.

 

 

Equivalent:

return 0;

return (0);

 

 

 

Screen Display

Hi Hi Hi Hi Hi
Please enter number (1-10)
3
Hi Hi Hi

 

 

 

 

   

 Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use | Resource CD