|
|
|
|
Function return values
A C++ function prototype must specify the
return value type of the function (in C, if you leave off the return value type
it defaults to int). The return type specification precedes the function
name. To specify that no value is returned, use the
void keyword. This will
generate an error if you try to return a value from the function. Here are some
complete function prototypes:
int f1(void); // Returns an int, takes no arguments
int f2(); // Like f1() in C++ but not in Standard C!
float f3(float, int, char, double); // Returns a float
void f4(void); // Takes no arguments, returns nothing
To return a value from a function, you
use the
return
statement. return exits the function back to the point right after the
function call. If return has an argument, that argument becomes the
return value of the function. If a function says that it will return a
particular type, then each return statement must return that type. You
can have more than one return statement in a function
definition:
//: C03:Return.cpp
// Use of "return"
#include <iostream>
using namespace std;
char cfunc(int i) {
if(i == 0)
return 'a';
if(i == 1)
return 'g';
if(i == 5)
return 'z';
return 'c';
}
int main() {
cout << "type an integer: ";
int val;
cin >> val;
cout << cfunc(val) << endl;
} ///:~
In cfunc( ), the first
if that evaluates to true exits the function via the return
statement. Notice that a function declaration is not necessary because the
function definition appears before it is used in main( ), so the
compiler knows about it from that function
definition.
|
|
|