Title: Functions
1Chapter 3
21. Introduction
- Experience has shown that the best way to develop
and maintain a large program is to construct it
from smaller pieces or components. - This chapter describes many key features of the
C language that facilitate the design,
implementation, operation, and maintenance of
large programs.
32. Program Components in C
- C programs are typically written by combining
new functions the programmer writes with
pre-packaged functions available in the C
standard library. - You need to familiarize yourself with the rich
collection of functions and classes in the C
standard library.
43. Math Library Functions
- Math library functions allow the programmer to
perform certain common mathematical calculations. - Functions are normally called by writing the name
of the function followed by a left parenthesis
followed by the argument (or comma separated
argument list) followed by a right parenthesis - cout ltlt sqrt ( 900.0 )
53. Math Library Functions (cont.)
- To use the math library functions include the
header file math.h (this header file is called
cmath in the new C standard library) - Forgetting to include the math header file when
using math library functions is an error. - Some math library functions are summarized in
Figure 3.2 (pg. 147)
64. Functions
- Functions allow the programmer to modularize a
program. - All variables declared in function definitions
are local variables -- they are known only in the
function in which they are defined. - Most functions have a list of parameters that
provide a means for communicating information
between functions. - A functions parameters are also local variables.
75. Function Definitions
- The format of a function definition is
ret-type func-name ( param-list)
declarations and statements - The return-type of void indicates that a function
does not return a value.
85. Function Definitions (cont.)
- The declarations and statements in braces form
the function body, or block. - Variables can be declared in any block
- There are three ways to return control to the
point at which a function was invoked. - when the function-ending right brace is reached
- return
- return expression
96. Function Prototypes
- A function prototype tells the compiler the name
of the function, the type of data returned by the
function, and the number of parameters the
function expects to receive, the types of these
parameters, and the order in which they are
expected. - The compiler uses function prototypes to validate
function calls.
106. Function Prototypes (cont.)
- Given the following prototype int maximum
(int, int, int) - This prototype states that maximum takes three
arguments of type int, and returns a result of
type int. - Another important feature of function prototypes
is the coercion of arguments (forcing of
arguments to the appropriate type)
117. Header Files
- Each standard library has a corresponding header
file containing the function prototypes for all
the functions in the library and definitions of
various data types and constants needed by these
functions. - Figure 3.6 (pg. 155) lists some common C
standard library header files that may be
included in C programs.
127. Header Files (cont.)
- Standard library header files are use by putting
the file name inside lt gt , for example include
ltstdlib.hgt - The programmer can create custom header files.
These should end in .h These are included by
putting the file name inside double quotes, for
example include square.h
138. Random Number Generation
- Consider the following statement i rand( )
- This generates an integer between 0 and RAND_MAX
(a symbolic constant defined in ltstdlib.hgt) - Scale the output with the modulus () operator
i rand( ) 6 This would produce numbers
from 0 to 5
148. Random Number Generation (cont.)
- The rand function actually produces pseudo-random
numbers. - You seed the random number generator by passing a
seed to the function srand ( ) srand( seed ) - Typically you seed it with the clock. srand (
time (0) )
159. A Game of Chance and Introducing enum
- The line enum Status CONTINUE, WON,
LOST creates a user-defined type called an
enumeration - Variables of type Status can only be defined one
of the values declared in the enumeration.
1610. Storage Classes
- C provides four storage class specifiers auto,
register, extern, and static. - An identifiers storage class determines the
period during which that identifier exists in
memory. - The storage class specifiers can be split into
two storage classes automatic storage class and
static storage class (dynamic will be discussed
later)
1710. Storage Classes (cont.)
- Automatic Storage Class.
- The auto and register keywords are used to
declare variables of the automatic storage class. - Such variables are created when the block in
which they are declared is entered, and they
exist while the block is active, and they are
destroyed when the block is exited. - the auto keyword is rarely used.
- the register keyword can be ignored by the
compiler.
1810. Storage Classes (cont.)
- Static Storage Class
- The keywords extern and static are used to
declare identifiers for variables and functions
of the static storage class. - Such variables exist from the point at which the
program begins execution until termination.
1910. Storage Classes (cont.)
- Static Storage Class (cont.)
- Local variables declared static are still known
only in the function in which they are defined,
but they retain their values when the function
exits. - In the following line static int count 1
the variable is initialized only one time. - extern and static are discussed in Chap. 18
2011. Scope Rules
- The portion of the program where an identifier
has meaning is known as its scope. - For example, when we declare a local variable in
a block, it can be referenced only in that block
(or blocks nested within that block) - Storage duration (or Lifetime) does not affect
the scope of an identifier.
2112. Recursion
- A recursive function is one that calls itself
either directly or indirectly through another
function. - Recursive functions have two parts
- Stopping Condition(s) -- solving the base
case(s). - Recursive call -- breaking the problem down.
2212. Recursion (cont.)
- long factorial ( long number )
if (number lt 1 ) // base case return
1 else // recursive case return
number factorial ( number -1 )
2313. Example Using Recursion The Fibonacci Series
- The Fibonacci series 0, 1,1,2,3,5,8,13,21,
begins with 0 and 1 and has the property that
each subsequent Fibonacci number is the sum of
the previous two. - The function to calculate the ith Fibonacci
number is quite naturally recursive. - What would the code for this would look like
2414. Recursion vs. Iteration
- Similarities
- Both iteration and recursion are based on a
control structure (iteration uses a repetition
structure recursion uses a selection structure) - Both iteration and recursion involve repetition
Iteration explicitly uses a repetition structure
recursion achieves repetition through repeated
function calls.
2514. Recursion vs. Iteration (cont.)
- Similarities (cont.)
- Iteration and recursion each involve a
termination test (iteration terminates when the
loop condition fails recursion terminates when a
base case is recognized). - Both iteration and recursion can occur
infinitely An infinite loop can occur with
iteration, and infinite recursion can occur when
the base case is not reached.
2614. Recursion vs. Iteration (cont.)
- Recursion has many negatives
- It repeatedly invokes the mechanism, and
consequently the overhead, of function calls. - This can be expensive in both terms of processor
time and memory. - So Why use recursion?
- some problems map very nicely to a recursive
solution. Thereby making code writing easier.
2715. Functions with Empty Parameter Lists
- In C, an empty parameter list is specified by
writing either void or nothing at all in
parentheses. The declaration void
print ( ) specifies that the
function print does not take any arguments and
does not return a value.
2816. Inline Functions
- Implementing a program as a set of functions is
good from a software engineering standpoint, but
function calls involve execution-time overhead. - C provides inline functions to help reduce
function-call overhead -- especially for small
functions.
2916. Inline Functions (cont.)
- The qualifier inline before a functions return
type advises the compiler to generate a copy of
the functions code in place (where appropriate)
to avoid a function call. - The tradeoff is larger compiled code.
- inline float cube ( const float s)
return s s s
3017. References and Reference Parameters
- Two ways to invoke functions in many programming
languages are call-by-value and
call-by-reference. - When an argument is passed call-by-value, a copy
of the arguments value is made and passed to the
called function. - With call-by-reference, the caller gives the
called function the ability to directly access
the callers data, and to modify it.
3117. References and Reference Parameters (cont.)
- Call-by-reference is good for performance reasons
because it eliminates the overhead of copying
large amounts of data. - A reference parameter is an alias for its
corresponding argument. - To indicate that a function parameter is passed
by reference, simply follow the parameters type
in the function prototype by an ampersand () and
use the same convention in the header.
3217. References and Reference Parameters (cont.)
- void sqr_by_ref( int cRef)
cRef cRef // cRef is changed - To specify a reference to a constant, place the
const qualifier before the type. This gives the
security of call-by-value but avoids the overhead
of copying a large object.
3317. References and Reference Parameters (cont.)
- References can also be used as aliases for other
variables within a function - int count 1 // variable int cRef count
// alias cRef //increments count
//using its alias - Reference variables must be initialized in their
declarations and cannot be reassigned to other
variables.
3418. Default Arguments.
- Function calls may commonly pass a particular
value of an argument. The programmer can specify
that such an argument is a default argument, and
can provide a default value for that argument. - When a default argument is omitted in a function
call, the default value of that argument is
automatically inserted by the compiler and passed
in the call.
3518. Default Arguments. (cont.)
- Default arguments must be the rightmost arguments
in the functions parameter list. - int boxVolume (int length 1, int width
1, int height 1) - Appropriate calls
- cout ltlt boxVolume()
- cout ltlt boxVolume(10)
- cout ltlt boxVolume(10, 5)
- cout ltlt boxVolume (10, 5, 2)
3619. Unary Scope Resolution Operator
- It is possible to declare local and global
variables of the same name. C provides the
unary scope resolution operator () to access a
global variable. - cout ltlt name // local variable cout ltlt
name // global variable - Example code pg. 189.
3720. Function Overloading
- C enables several functions of the same name to
be defined as long as these functions have
different sets of parameters (at least as far as
their types are concerned) - Overloading functions that perform closely
related tasks can make the program more readable
and understandable.
3821. Function Templates
- Overloaded functions are normally used to perform
similar operations that involve different program
logic on different data types. - If the program logic and operations are identical
for each data type, this may be performed more
compactly and conveniently using function
templates.
3921. Function Templates (cont.)
- All function template definitions begin with the
template keyword followed by a list of formal
type parameters to the function enclosed in angle
brackets (lt and gt). - Every formal type parameter is preceded by the
class keyword. - The function definition follows and is defined
like any other function.
4021. Function Templates (cont.)
- Example template ltclass Tgt T maximum
(T val1, T val2) T max
val1 if (val2 gt max) max val2
return max
4121. Function Templates (cont.)
- Sample calls
- cout ltlt maximum(1,2)
- cout ltlt maximum (3.5, 4.7)
- cout ltlt maximum (c, h)
- With this code, three functions are created and
compiled, one for integers, one for doubles, and
one for characters.