The return type of a function can be a built-in type, such as int or double, a class type, or a compound type, such as int& or string*. A return type also can be void, which means that the function does not return a value. The following are example definitions of possible function return types:
- bool is_present(int *, int); // returns bool
- int count(const string &, char); // returns int
- Date &calendar(const char*); // returns reference to Date
- void process(); // process does not return a value
A function may not return another function or a built-in array type. Instead, the function may return a pointer to the function or to a pointer to an element in the array:
C++(www.cppentry.com) 中的函数和数组不是一等公民类型。
- // ok: pointer to first element of the array
- int *foo_bar() { /* . . . */ }
This function returns a pointer to int and that pointer could point to an element in an array.
We’ll learn about function pointers in Section 7.9 (p. 276).
Functions Must Specify a Return Type
It is illegal to define or declare a function without an explicit return type:
- // error: missing return type
- test(double v1, double v2) { /* . . . */ }
Eariler versions of C++(www.cppentry.com) would accept this programand implicitly define the return type of test as an int. Under Standard C++(www.cppentry.com), this program is an error.
In pre-Standard C++(www.cppentry.com), a function without an explicit return type was assumed to return an int. C++(www.cppentry.com) programs compiled under earlier, nonstandard compilers may still contain functions that implicitly return int.