Functions are the building blocks of C and C++ and the place where all program
activity occurs. This chapter examines their C-like features, including passing
arguments, returning values, prototypes, and recursion. Part Two discusses
the C++-specific features of functions, such as function overloading and reference
parameters.
activity occurs. This chapter examines their C-like features, including passing
arguments, returning values, prototypes, and recursion. Part Two discusses
the C++-specific features of functions, such as function overloading and reference
parameters.
The General Form of a Function
The general form of a function is
ret-type function-name(parameter list)
{
body of the function
}
The ret-type specifies the type of data that the function returns.Afunction may return
any type of data except an array. The parameter list is a comma-separated list of variable
names and their associated types that receive the values of the arguments when the
function is called.Afunction may bewithout parameters, in which case the parameter
list is empty. However, even if there are no parameters, the parentheses are still required.
In variable declarations, you can declare many variables to be of a common type
by using a comma-separated list of variable names. In contrast, all function parameters
must be declared individually, each including both the type and name. That is, the
parameter declaration list for a function takes this general form:
f(type varname1, type varname2, . . . , type varnameN)
For example, here are correct and incorrect function parameter declarations:
f(int i, int k, int j) /* correct */
f(int i, k, float j) /* incorrect */
No comments:
Post a Comment