Returning Data from Functions:
A function can return only one value. It can be of any type except string and array. The type of data that a user-defined function returns is declared in function declaration. The value or data is returned from the function to the calling function by the “return” statement.
Return Statement:
The “return” statement is used to return the calculated value from function definition to the calling function. In some compilers of C and C++, it is used as a last statement of body of the function to return the control as well as to return the calculated value to the calling function. Its syntax is:
where
expression: represents an arithmetic expression or constant value. The value of the expression is returned to the calling function.
If the function has a “void” return data type, then the use of this statement is optional.
Declaration of Function that Returns a Value:
The type of a function specifies the type of the data returned by it. It is specified in the function declaration. It is also called the data type of the function. The data type of a function is declared in the same way as the type of a variable is declared, e.g.
In the above function declaration;
temp: name of the function.
float: returned data type.
void: in the brackets specifies that it has no arguments.
Calling a Function that Returns a Value:
The function that returns a value can be called in an arithmetic expression. In this case the function is treated as a variable. Similarly, the value returned by the function may be assigned to a variable or it can be directly sent to an output device, i.e. printer, screen or file. For example, to assign the returned value of the function “temp” to a variable “r’ the statement is written as:
Where “r” is a variable that receives the returned value of’ function “temp”. Since the function will return float type value, the variable “r” should also be of float type.
To print the returned value directly on the screen, the function “temp” is called as:
cout << “The returned value is” << temp ( );
Function Definition that Return a Value:
The function that returns a value is defined in the similar way as other functions are defined hut in the decelerator the return data type is mentioned. The returned data type must be the same as mentioned in the function declaration. The “return” statement must be used in the function body to return the value to the calling function.
comment closed