Returning a Value

<< Click to Display Table of Contents >>

Navigation:  Concordance Programming Fundamentals > Writing a Function >

Returning a Value

A function can optionally return a single value. Returning a value means that, when a function ends, the function will give back a value. Most commonly, the value that is returned is then assigned to a variable of some sort, as described in Calling a Function.

To return a value from a function

At the end of the function, use the return() command to indicate what you wish to return.

Calling the return command ends the function; any additional code after the return() command will be ignored.

The following example shows how to return the value z from a function.

Multiply_X_by_Y(int x, int y)

{

   int z;

   z = x * y;

   return(z);
}

 

You do not need to use a return value. For example, if you designed a function to access the Concordance database or perform a calculation and display the result to the user, there may be no reason to return a value. However, many functions will return a value of some sort.

In most programming languages, you have to declare a function by also specifying the type of the parameter you are returning. You would find the function in the above example declared in C as:

 

int Multiply_X_by_Y(int x, int y)

 

This tells the C language interpreter to expect an integer as a return value. However, CPL does not use this convention. You do not have to specify the type of the return value. You must however be careful to remember the type of the return value, if any. If you call the function expecting to get a short and get an int instead, you may wind up with some unexpected results.

Once you have finished your function, you can use your function in a function call. For more information, see Calling a Function.