|
When a function completes its execution, it
can return a single value to the calling program, which can
be trapped when the calling function needs the result of the
called function. The following program illustrates a
function that returns a value:
//Program 7.8
//This program uses a function to add two numbers and
returns the sum to the calling program
#include<iostream.h>
int add(int, int); //This function returns a value of type
int
void main()
{
int iSum1, iVar1, iVar2;
cout<<"Enter two numbers "<<endl;
cin>>iVar1;
cin>>iVar2;
iSum1 = add(iVar1, iVar2);
cout<<"The sum of the two numbers is "<<iSum1<<endl;
}
int add(int iNum1, int iNum2)
{
return iNum1+iNum2;
}
When a function returns a value, the data type of the value
must be specified. In Program 7.8, the type int is placed
before the function add(). Function in the earlier program
returned no value, therefore the return type was void.
The statement:
iSum1 = add(iVar1, iVar2)
causes the variable iSum1 to be assigned the value returned
by the function add().
The sample output of Program 7.8 is:
Enter two numbers
23
37
The sum of the two number is 60 |