Title: ECE206 Programming
1ECE206 - Programming
- Lecture 12 Function (Advanced Features)
- 11/13/07
2What do you need to know
- Fundamentals
- Function declaration
- Forward prototype
- Forward definition
- Call-by-value vs. call-by-reference
- Command-line arguments
- Storage class
- Advanced topics
- Function overloading
- Inline functions
- Functions with default augments
- Function templates
- Recursive functions
- Function pointer
3C storage classes - revisit
- Each C variable has several attributes
- name, type, size, value
- storage class, scope, linkage
- C has four storage classes
- auto the default. Variables are automatically
created and initialized when they are defined and
are destroyed at the end of the block containing
their definition. They are not visible outside
that block. - register a type of auto variable. a suggestion
to the compiler to use a CPU register for
performance. - static a variable that is known only in the
function that contains its definition but is
never destroyed and retains its value between
calls to that function. It exists from the time
the program begins execution. - extern a static variable whose definition and
placement is determined when all object and
library modules are combined (linked) to form the
executable code file. It can be visible outside
the file where it is defined.
4Example - register
include ltctimegt register int i, j int
starttime, endtime starttime clock() for
(i0 iltLARGENUM i) endtime clock() cout
ltlt the duration is ltlt endtime starttime
5A few more things about register
- A modern processor normally has at least 32
registers for integer variables and 32 registers
for floating point variables - Each register is 32 bit or 64 bit depending on
different computer architectures - An optimized compiler should allocate the most
frequently accessed variables in the register
with or without explicitly specifying register
storage class - Theres only limited amount of registers. What
if all the registered are occupied?
6Example static variables
// compute a running avg. of numbers entered by
user include ltiostreamgt using namespace
std float r_avg(int i) int main() int
num do cout ltlt Enter numbers (-1 to
quit) cin gtgt num cout ltlt Running
average is ltlt r_avg(num) cout ltlt \n
while (num gt -1) return 0
float r_avg(int i) static float sum 0
static int count 0 sum i
count return sum / count
7Another example
int ComplexgetCount() return count //
method implementation ComplexComplex() real
0 imag 0 count ComplexComplex(float
a, float b) real a imag
b count ComplexComplex() count--
// class definition class Complex
public Complex() Complex(float,
float) Complex() void setComplex(float,
float) void printComplex() float getReal()
const float getImag() const void
setReal(float) void setImag(float) static
int getCount() private float real float
imag static int count
8Inline functions
- Short frequently used functions are good
candidates for inline functions. - An inline functions body is inserted directly in
the compiled code at the point where the function
would normally be called. - The advantage is efficiency.
- Like the register keyword, inline is only a
suggestion to the compiler.
9Example
// using inline function to calculate the volume
of a cube include ltiostreamgt using namespace
std inline float cube(float s) return s s
s int main() float side cin gtgt
side cout ltlt The volume of cube with side
ltlt side ltlt is ltlt cube(side)
return 0
10System software revisit
- Preprocessor
- Occurs before compilation begins
- Used for inclusion of other files in the file
being compiled - Used for definition of symbolic constants and
macros - Conditional compilation
- ifndef.endif
- Compiler
- Creates object codes
- Linker
11Default arguments
- Default arguments have a defined value if they
are not present in the calling parameter list. - Default argument must be the rightmost parameters
(so they can be omitted). - Default arguments must be specified only once
(first appearance of function name, usually in
function prototype).
12Example
// inline function definition inline int volume
(int length, int width 1, int
height 1) return length width
height int main() int v1, v2, v3
v1 volume (1,5) // value is 5 v2
volume (4) // value is 4 v3 volume
(2,2,2) // value is 8
No function call!!! Multiple copies of the
function implementation in the object code
v1 1 5 1 v2 4 1 1 v3 2 2 2
13Function overloading
- One of Cs most exciting feature
- C allows several functions with the same name
to be defined, as long as the types and/or
numbers of their arguments differ. - The functions that share the same name are said
to be overloaded - Function overloading is one way that C achieves
polymorphism
14Example
// overloading abs() include ltiostreamgt using
namespace std // abs() is overloaded in two
ways int abs(int i) double abs(double d) int
main() cout ltlt abs(-10) ltlt \n cout
ltlt abs(-11.0) ltlt \n return 0 int
abs(int i) if (ilt0) return -i else
return i double abs(double d) if
(dlt0.0) return -d else return d
- Consider 2 functions located in the standard
library abs(), fabs(). - They are first defined by the C language, and for
compatibility, are also included in C. - So for similar tasks, programmer has two names to
remember, not just one. - C can resolve this problem by function
overloading
15 Function Templates
- Function templates allow the definition of
functions independent of the type of the
arguments and return value. - This implements a philosophy of write-once /
use-anywhere by allowing parameterized types. - Templates form the basis for the C Standard
Template Library (STL) of algorithms, which we
will discuss later.
16 A Function Template Example
int maximum ( int value1, int value2, int value3
) int max value1 if ( value2 gt max )
max value2 if ( value3 gt max )
max value3 return max
int main() int a1,b3,c3 int m m
maximultintgt(a, b, c) return 0
template ltclass Tgt T maximum ( T value1, T
value2, T value3 ) T max value1 if (
value2 gt max ) max value2 if (
value3 gt max ) max value3 return
max
A list of formal type parameters, preceded by the
class keyword, is specified between the ltgt,
and is used in place of types in the function
definition.
17 Recursion
- Recursive functions calls itself (directly or
through another function). - Any C function call call itself, but functions
that use static and extern variables must do so
carefully. - Recursion can be used to solve problems by
induction - Do one step, and call itself to solve the
remaining problem. - Detect and perform the last step (base case).
18 Factorial a recursive example
- The factorial of a positive integer, n!, is the
product of all integers between 1 and n,
inclusive. - The factorial can also be defined in terms of
itself - For ngt0, n! n (n-1)!
- For n0, n! 1
- This can be translated directly to a C
implementation.
19 Recursive factorial in C
int factorial (int n) if (n0)
return 1 //do the last step else if (ngt0)
return nfactorial(n-1) //do one step
else return -1 //indicator of error
(nlt0)
Many problems can be solved using this same
structure Take care of the last step and
possible error conditions, and then do one
(simple) step.
20Recursive process
Factorial(3)
3Factorial(2)
2Factorial(1)
1Factorial(0)
11
21
32
6
21 Pros and cons of using recursive functions
- If an algorithm can be expressed in a recursive
form with a simple algorithm for each step, the
recursive implementation can be very easy to
verify. - Recursion incurs overhead in creation and
destruction of automatic variables and in
function calls. - Recursion may hide gross inefficiencies (e.g.,
the Fibonacci example) watch for explosive
numbers of recursive calls!
22 Recursive Fibonacci calculation
long fib (long n) if ( n 0 n 1 )
return n //base case
else if ( n gt 0 ) return fib(n-1)
fib(n-2) //recursive case else
return -1 //error case
Each call to fib (except fib(0) and fib(1))
generates 2 more calls to fib, which generates
an exponential explosion in the total number of
calls to fib as n increases. Let
O(fib,n) be the number of calls required to
calculate fib(n) Then O(fib,n) 1
O(fib,n-1) O(fib,n-2).