CS110 Lab: C++ Value-returning Functions


Here is the syntax template of a value-returning function prototype:

    
returnDataType functionName(Parameter_DataType_List);

Here is the syntax template of a value-returning function definition:

    
returnDataType functionName(ParameterList)
{
	// Statements
	    .
	    .
	    .
	return value-returning-expression;
}

With void functions, we use the function name as a statement in our program to execute the actions that function performs. With value-returning functions, the actions result in the return of a value, and that value can be used in an expression. For example, let's write a function that returns the smallest of three input values.

Example

    
// Program printMin prints the smallest of three input values.

#include <iostream>
using namespace std;

// minimum returns the minimum of three distinct values.
int  minimum(int, int, int);	// function prototype

int main()
{
    int  one, two, three;
    int  min;

    cout << "Input three integer values. Press return." << endl;
    cin  >> one  >> two  >> three;
    min = minimum(one, two, three); // function call 
    cout  << "The minimum value of the three numbers is " << min << endl;

    return 0;
}


//************************************************************
//Function definition with 3 parameters
//************************************************************
// Post: Returns minimum of three distinct int values.
int  minimum(int first, int second, int third)
{
    if (first <= second && first < third)
	    return first;
    else if (second <= first && second < third)
	    return second;
    else 
	    return third;
}

The function prototype declares a function of data type int. This means that the value returned to the calling function is of type int. Because a value-returning function always sends one value back to the calling function, we designate the type of the value before the name of the function. We call this data type the function return data type or function type.

In the above example, the function invocation/call occurs in the output statement of the main() function. The minimum() function is invoked/called and the returned value is immediately sent to the output stream. There are three parameters first, second and third. The three arguments sent from main are one, two and three. Note: in the function prototype, only the datatypes of the parameter list are needed. In the function heading (or function definition), however, both the parameters and their datatype are necessary.

 


 

© Department of Computer Science, University of Regina.