next up previous
Next: Local/Global Up: Functions Previous: Function Arguments

Functions Returning Values

In C++, a function uses a return statement to return a value. The general form of return is :

return value;

where value is the value being returned.

Example
//returning a value
#include <iostream.h>

mul(int x, int y); // mul() prototype void is not used
main()
{
int answer;
answer=mul(10,11);// assign return value cout << "The answer is " << answer;
return 0; // this one for main() }
/* This function returns a value */
mul(int x, int y) {
return x*y; // return the product of x and y }

A function can be declared to return any valid C++ data type, except that a function cannot return an array. The method of declaration is similar to that used with variables: The type specifier precedes the function name. The type specifier tells the compiler what type of data will be returned by the function. This return type must be compatible with the type of data used in the return statement. If not a compile time error will result. The return type of a function precedes its name in both its prototype and its definition. If no return type is specified then the function is assumed to return an integer value.

Example
// declaring return data type in functions
#include <iostream.h>
int sqr_it(int x); // declares the return data type as an integer
main()
{
int t=10;
cout << sqr_it(t) <<' '<<t;
return 0;
}
sqr_it(int x)
{
x=x*x;
return x;
}

The function argument and the function return value can be of different types for example the argument can be integer and the return value can be float, or any other type. If the type of returned value is not declared, by default the function is assumed to return an integer value.

Example
#include <iostream.h>
float avg(int a, int b); // prototype
main()
{
avg(12,13);
avg(15,12);
}
float avg(int a, int b)
{
return((a+b)/2.0);
}


next up previous
Next: Local/Global Up: Functions Previous: Function Arguments
Yousef Haik
2/23/1998