CS110 Lab: C++ Value-returning Functions

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

returnDataType functionName(DataTypeOfParameterList);

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

returnDataType functionName(DataTypeWithParameterList)
	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.


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

#include <iostream>
using namespace std;

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

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

int  Minimum(int first, int second, int third)
// Post: Returns minimum of three distinct int values.
    if (first <= second && first < third)
	return first;
    else if (second <= first && second < third)
	return second;
	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.

Copyright: Department of Computer Science, University of Regina.