Professional Documents
Culture Documents
COEN 244 - 6 - Functions
COEN 244 - 6 - Functions
6
Functions
Function Components
A function consists of function
prototype, function header and
function body.
Functions often require more than one
piece of information to perform their
tasks, which is passed by parameters.
Parameters are specified in both the
function prototype and the function
header.
Function prototype
Also called a function declaration
Indicates to the compiler:
Name of the function
Type of data returned by the function
Parameters the function expects to receive
Types of those parameters
Order of those parameters
Function Header
Same as function prototype but it also
includes the name of the parameters.
Example: int max(int x, int y, int z)
parameter names: x, y, z
Function Body
Function body begins with a left brace
following the function header and ends
with a right brace.
Ex:
int max(int x, int y, int z)
{ int maxValue = x;
if ( y > maxValue) maxValue = y;
if( z > maxValue) maxValue = z;
return maxValue }
Function Execution
A function is invoked by a function call
Following a call, statements within the
function body will execute
Ex: max (grade1, grade2, grade3)
argumets : grade1, grade2, grade3
Identifiers scope
Determines where the identifier can be
referenced in a program
Variables
Local : These are variables defined
within a function. They will be visible
only within the function. They exist only
during the execution of a function
(exception static local variables).
Global: These are variables defined
outside of all the functions. They will be
visible in all the functions and they exist
during the entire execution.
10
11
Argument Coercion
Forcing arguments to the appropriate types specified by
the corresponding parameters
For example, calling a function with an integer argument,
even though the function prototype specifies a double
argument
Ex: double sqrt( double x)
int x = 10;
sqrt( x);
The function will still work correctly
12
y = x;
x = y;
13
14
15
16
17
18
19
20