Up and Running
17
You declare functions according to the general syntax shown in
Listing 1-5.
return-type
u
function_name
v
(
par-type1 par_name1
w
,
par-type2
par_name2
x
) {
--
snip
--
return
y
return-value
;
}
Listing 1-5: The general syntax for a C++ function
The first part of this function declaration is the type of the return vari-
able
u
, such as
int
. When the function returns a value
y
, the type of
return-
value
must match
return-type
.
Then you declare the function’s name
v
after declaring the return
type. A set of parentheses following the function name contains any num-
ber of comma-separated input parameters that the function requires. Each
parameter also has a type and a name.
Listing 1-5 has two parameters. The first parameter
w
has type
par-type1
and is named
par_name1
, and the second parameter
x
has type
par-type2
and
is named
par_name2
. Parameters represent the objects passed into a function.
A set of braces following that list contains the function’s body. This is a
compound statement that contains the function’s logic. Within this logic, the
function might decide to return a value to the function’s caller. Functions
that return values will have one or more
return
statements. Once a function
returns, it stops executing, and the flow of the program returns to whatever
called the function. Let’s look at an example.
Dostları ilə paylaş: