Sams Teach Yourself C in 21 Days

(singke) #1
Packaging Code in Functions 101

5


execution passes back to the place from which the function was called. A function can be
called as many times as needed, and functions can be called in any order.

FIGURE5.1
When a program calls
a function, execution
passes to the function
and then back to the
calling program.

main()
{
call func1
...
call func2
...
call func3

}

func1()
{
}

func2()
{
}

func3()
{
}

Main program

You now know what a function is and the importance of functions. Lessons on how to
create and use your own functions follow.

Functions
Function Prototype
return-type function_name( arg-type name-1,...,arg-type name-n);
Function Definition
return-type function_name( arg-type name-1,...,arg-type name-n)
{
/* statements; */
}
Afunction prototypeprovides the compiler with a description of a function that will be
defined at a later point in the program. The prototype includes a return type indicating
the type of variable that the function will return. It also includes the function name,
which should describe what the function does. The prototype also contains the variable
types of the arguments (arg-type) that will be passed to the function. Optionally, it can
contain the names of the variables that will be passed. A prototype should always end
with a semicolon.
Afunction definitionis the actual function. The definition contains the code that will be
executed. If the prototype contains the names of the variables, the first line of a function
definition, called the function header,should be identical to the function prototype, with
the exception of the semicolon. A function header shouldn’t end with a semicolon. In
addition, although the argument variable names were optional in the prototype, they must

,


S

YNTAX

,


09 448201x-CH05 8/13/02 11:15 AM Page 101

Free download pdf