C++ Learning Resource Network!

 C++ Tutorials  >  Functions  >  return Values from Functions

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
int add(int, int); //This function returns a value of type int
void main()
int iSum1, iVar1, iVar2;
cout<<"Enter two numbers "<<endl;
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
The sum of the two number is 60


| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.