5
C Functions
1
© 2007 Pearson Education, Inc. All rights reserved.
Form ever follows function.
—Louis Henri Sullivan
E pluribus unum.�(One composed of many.)
—Virgil
O! call back yesterday, bid time return.
—William Shakespeare
Call me Ishmael.
—Herman Melville
2
© 2007 Pearson Education, Inc. All rights reserved.
When you call me that, smile!
—Owen Wister
Answer me in one word.
—William Shakespeare
There is a point at which methods devour themselves.
—Frantz Fanon
Life can only be understood backward; but it must be lived forward.
—Soren Kierkegaard
3
© 2007 Pearson Education, Inc. All rights reserved.
OBJECTIVES
In this chapter you will learn:
4
© 2007 Pearson Education, Inc. All rights reserved.
5.1 Introduction
5.2 Program Modules in C
5.3 Math Library Functions
5.4 Functions
5.5 Function Definitions
5.6 Function Prototypes
5.7 Function Call Stack and Activation Records
5.8 Headers
5.9 Calling Functions: Call-by-Value and Call-by- Reference
5
© 2007 Pearson Education, Inc. All rights reserved.
5.10 Random Number Generation
5.11 Example: A Game of Chance
5.12 Storage Classes
5.13 Scope Rules
5.14 Recursion
5.15 Example Using Recursion: Fibonacci Series
5.16 Recursion vs. Iteration
6
© 2007 Pearson Education, Inc. All rights reserved.
5.1 Introduction
7
© 2007 Pearson Education, Inc. All rights reserved.
5.2 Program Modules in C
Worker gets information, does task, returns result
Information hiding: boss does not know details
8
© 2007 Pearson Education, Inc. All rights reserved.
Good Programming Practice 5.1
Familiarize yourself with the rich collection of functions in the C Standard Library.
9
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.1
Avoid reinventing the wheel. When possible, use C Standard Library functions instead of writing new functions. This can reduce program development time.
10
© 2007 Pearson Education, Inc. All rights reserved.
Portability Tip 5.1
Using the functions in the C Standard Library helps make programs more portable.
11
© 2007 Pearson Education, Inc. All rights reserved.
12
Fig. 5.1 | Hierarchical boss function/worker function relationship.
© 2007 Pearson Education, Inc. All rights reserved.
5.3 Math Library Functions
13
© 2007 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 5.1
Include the math header by using the preprocessor directive #include <math.h> when using functions in the math library.
14
© 2007 Pearson Education, Inc. All rights reserved.
15
Fig. 5.2 | Commonly used math library functions. (Part 1 of 2.)
© 2007 Pearson Education, Inc. All rights reserved.
16
Fig. 5.2 | Commonly used math library functions. (Part 2 of 2.)
© 2007 Pearson Education, Inc. All rights reserved.
5.4 Functions
17
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.2
In programs containing many functions, main is often implemented as a group of calls to functions that perform the bulk of the program’s work.
18
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.3
Each function should be limited to performing a single, well-defined task, and the function name should effectively express that task. This facilitates abstraction and promotes software reusability.
19
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.4
If you cannot choose a concise name that expresses what the function does, it is possible that your function is attempting to perform too many diverse tasks. It is usually best to break such a function into several smaller functions.
20
© 2007 Pearson Education, Inc. All rights reserved.
5.5 Function Definitions
return-value-type function-name( parameter-list )�{� declarations and statements�}
21
© 2007 Pearson Education, Inc. All rights reserved.
5.5 Function Definitions
return-value-type function-name( parameter-list )�{� declarations and statements�}
return;
or, until reaches right brace
return expression;
22
© 2007 Pearson Education, Inc. All rights reserved.
Good Programming Practice 5.2
Place a blank line between function definitions to separate the functions and enhance program readability.
23
© 2007 Pearson Education, Inc. All rights reserved.
24
Outline
fig05_03.c
Function definition
Function prototype indicates function will be defined later in the program
Call to square function
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.1
Omitting the return-value-type in a function definition is a syntax error if the function prototype specifies a return type other than int.
25
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.2
Forgetting to return a value from a function that is supposed to return a value can lead to unexpected errors. The C standard states that the result of this omission is undefined.
26
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.3
Returning a value from a function with a void return type is a syntax error.
27
© 2007 Pearson Education, Inc. All rights reserved.
Good Programming Practice 5.3
Even though an omitted return type defaults to int, always state the return�type explicitly.
28
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.4
Specifying function parameters of the same type as double x, y instead of double x, double y might cause errors in your programs. The parameter declaration double x, y would actually make y a parameter of type int because int is the default.
29
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.5
Placing a semicolon after the right parenthesis enclosing the parameter list of a function definition is a syntax error.
30
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.6
Defining a function parameter again as a local variable within the function is a syntax error.
31
© 2007 Pearson Education, Inc. All rights reserved.
Good Programming Practice 5.4
Include the type of each parameter in the parameter list, even if that parameter is of the default type int.
32
© 2007 Pearson Education, Inc. All rights reserved.
Good Programming Practice 5.5
Although it is not incorrect to do so, do not use the same names for the arguments passed to a function and the corresponding parameters in the function definition. This helps avoid ambiguity.
33
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.7
Defining a function inside another function is a syntax error.
34
© 2007 Pearson Education, Inc. All rights reserved.
Good Programming Practice 5.6
Choosing meaningful function names and meaningful parameter names makes programs more readable and helps avoid excessive use of comments.
35
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.5
A function should generally be no longer than one page. Better yet, functions should generally be no longer than half a page. Small functions promote software reusability.
36
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.6
Programs should be written as collections of small functions. This makes programs easier to write, debug, maintain and modify.
37
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.7
A function requiring a large number of parameters may be performing too many tasks. Consider dividing the function into smaller functions that perform the separate tasks. The function header should fit on one line if possible.
38
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.8
The function prototype, function header and function calls should all agree in the number, type, and order of arguments and parameters, and in the type of return value.
39
© 2007 Pearson Education, Inc. All rights reserved.
40
Outline
fig05_04.c
(1 of 2 )
Function prototype
Function call
© 2007 Pearson Education, Inc. All rights reserved.
41
Outline
fig05_04.c
(2 of 2 )
Function definition
© 2007 Pearson Education, Inc. All rights reserved.
5.6 Function Prototypes
int maximum( int x, int y, int z );
42
© 2007 Pearson Education, Inc. All rights reserved.
Good Programming Practice 5.7
Include function prototypes for all functions to take advantage of C’s type-checking capabilities. Use #include preprocessor directives to obtain function prototypes for the standard library functions from the headers for the appropriate libraries, or to obtain headers containing function prototypes for functions developed by you and/or your group members.
43
© 2007 Pearson Education, Inc. All rights reserved.
Good Programming Practice 5.8
Parameter names are sometimes included in function prototypes (our preference) for documentation purposes. The compiler ignores these names.
44
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.8
Forgetting the semicolon at the end of a function prototype is a syntax error.
45
© 2007 Pearson Education, Inc. All rights reserved.
46
Fig. 5.5 | Promotion hierarchy for data types.
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.9
Converting from a higher data type in the promotion hierarchy to a lower type can change the data value.
47
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.10
Forgetting a function prototype causes a syntax error if the return type of the function is not int and the function definition appears after the function call in the program. Otherwise, forgetting a function prototype may cause a runtime error or an unexpected result.
48
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.9
A function prototype placed outside any function definition applies to all calls to the function appearing after the function prototype in the file. A function prototype placed in a function applies only to calls made in that function.
49
© 2007 Pearson Education, Inc. All rights reserved.
5.7 Function Call Stack and Activation Records
50
© 2007 Pearson Education, Inc. All rights reserved.
5.8 Headers
#include <math.h>
51
© 2007 Pearson Education, Inc. All rights reserved.
52
Fig. 5.6 | Some of the standard library headers. (Part 1 of 3.)
© 2007 Pearson Education, Inc. All rights reserved.
53
Fig. 5.6 | Some of the standard library headers. (Part 2 of 3.)
© 2007 Pearson Education, Inc. All rights reserved.
54
Fig. 5.6 | Some of the standard library headers. (Part 3 of 3.)
© 2007 Pearson Education, Inc. All rights reserved.
5.9 Calling Functions: Call-by-Value and Call-by-Reference
55
© 2007 Pearson Education, Inc. All rights reserved.
5.10 Random Number Generation
i = rand();
1 + ( rand() % n )
1 + ( rand() % 6)
number between 1 and 6
56
© 2007 Pearson Education, Inc. All rights reserved.
57
Outline
fig05_07.c
Generates a random number between 1 and 6
© 2007 Pearson Education, Inc. All rights reserved.
58
Outline
fig05_08.c
(1 of 3 )
© 2007 Pearson Education, Inc. All rights reserved.
59
Outline
fig05_08.c
(2 of 3 )
© 2007 Pearson Education, Inc. All rights reserved.
60
Outline
fig05_08.c
(3 of 3 )
© 2007 Pearson Education, Inc. All rights reserved.
5.10 Random Number Generation
srand( seed );
Returns the number of seconds that have passed since January 1, 1970
“Randomizes" the seed
61
© 2007 Pearson Education, Inc. All rights reserved.
62
Outline
fig05_09.c
(1 of 2 )
Seeds the rand function
© 2007 Pearson Education, Inc. All rights reserved.
63
Outline
fig05_09.c
(2 of 2 )
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.11
Using srand in place of rand to generate random numbers.
64
© 2007 Pearson Education, Inc. All rights reserved.
5.11 Example: A Game of Chance
65
© 2007 Pearson Education, Inc. All rights reserved.
66
Outline
fig05_10.c
(1 of 4 )
enum (enumeration) assigns numerical values to CONTINUE, WON and LOST
© 2007 Pearson Education, Inc. All rights reserved.
67
Outline
fig05_10.c
(2 of 4 )
© 2007 Pearson Education, Inc. All rights reserved.
68
Outline
fig05_10.c
(3 of 4 )
© 2007 Pearson Education, Inc. All rights reserved.
69
Outline
fig05_10.c
(4 of 4 )
© 2007 Pearson Education, Inc. All rights reserved.
70
Outline
fig05_11.c
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.12
Assigning a value to an enumeration constant after it has been defined is a syntax error.
71
© 2007 Pearson Education, Inc. All rights reserved.
Good Programming Practice 5.9
Use only uppercase letters in the names of enumeration constants to make these constants stand out in a program and to indicate that enumeration constants are not variables.
72
© 2007 Pearson Education, Inc. All rights reserved.
5.12 Storage Classes
auto double x, y;
register int counter = 1;
73
© 2007 Pearson Education, Inc. All rights reserved.
Performance Tip 5.1
Automatic storage is a means of conserving memory, because automatic variables exist only when they are needed. They are created when the function in which they are defined is entered and they are destroyed when the function is exited.
74
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.10
Automatic storage is an example of the principle of least privilege—allowing access to data only when it is absolutely needed. Why have variables stored in memory and accessible when in fact they are not needed?
75
© 2007 Pearson Education, Inc. All rights reserved.
Performance Tip 5.2
The storage-class specifier register can be placed before an automatic variable declaration to suggest that the compiler maintain the variable in one of the computer’s high-speed hardware registers. If intensely used variables such as counters or totals can be maintained in hardware registers, the overhead of repeatedly loading the variables from memory into the registers and storing the results back into memory can be eliminated.
76
© 2007 Pearson Education, Inc. All rights reserved.
Performance Tip 5.3
Often, register declarations are unnecessary. Today’s optimizing compilers�are capable of recognizing frequently used variables and can decide to place them in registers without the need for a register declaration.
77
© 2007 Pearson Education, Inc. All rights reserved.
5.12 Storage Classes
78
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.11
Defining a variable as global rather than local allows unintended side effects to occur when a function that does not need access to the variable accidentally or maliciously modifies it. In general, use of global variables should be avoided except in certain situations with unique performance requirements (as discussed in Chapter 14).
79
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.12
Variables used only in a particular function should be defined as local variables in that function rather than as external variables.
80
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.13
Using multiple storage-class specifiers for an identifier. Only one storage-class specifier can be applied to an identifier.
81
© 2007 Pearson Education, Inc. All rights reserved.
5.13 Scope Rules
82
© 2007 Pearson Education, Inc. All rights reserved.
5.13 Scope Rules
83
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.14
Accidentally using the same name for an identifier in an inner block as is used for an identifier in an outer block, when in fact you want the identifier in the outer block to be active for the duration of the inner block.
84
© 2007 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 5.2
Avoid variable names that hide names in outer scopes. This can be accomplished simply by avoiding the use of duplicate identifiers in a program.
85
© 2007 Pearson Education, Inc. All rights reserved.
86
Outline
fig05_12.c
(1 of 4 )
Global variable with file scope
Variable with block scope
Variable with block scope
© 2007 Pearson Education, Inc. All rights reserved.
87
Outline
fig05_12.c
(2 of 4 )
Variable with block scope
© 2007 Pearson Education, Inc. All rights reserved.
88
Outline
fig05_12.c
(3 of 4 )
Static variable with block scope
Global variable
© 2007 Pearson Education, Inc. All rights reserved.
89
Outline
fig05_12.c
(4 of 4 )
© 2007 Pearson Education, Inc. All rights reserved.
5.14 Recursion
What it cannot do resembles original problem
The function launches a new copy of itself (recursion step) to solve what it cannot do
90
© 2007 Pearson Education, Inc. All rights reserved.
5.14 Recursion
91
© 2007 Pearson Education, Inc. All rights reserved.
92
Fig. 5.13 | Recursive evaluation of 5!.
© 2007 Pearson Education, Inc. All rights reserved.
93
Outline
fig05_14.c
(1 of 2 )
© 2007 Pearson Education, Inc. All rights reserved.
94
Outline
fig05_14.c
(2 of 2 )
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.15
Forgetting to return a value from a recursive function when one is needed.
95
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.16
Either omitting the base case, or writing the recursion step incorrectly so that it does not converge on the base case, will cause infinite recursion, eventually exhausting memory. This is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution. Infinite recursion can also be caused by providing an unexpected input.
96
© 2007 Pearson Education, Inc. All rights reserved.
5.15 Example Using Recursion: Fibonacci Series
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1) +� fibonacci( n – 2 );
}
97
© 2007 Pearson Education, Inc. All rights reserved.
98
Outline
fig05_15.c
(1 of 4 )
© 2007 Pearson Education, Inc. All rights reserved.
99
Outline
fig05_15.c
(2 of 4 )
© 2007 Pearson Education, Inc. All rights reserved.
100
Outline
fig05_15.c
(3 of 4 )
© 2007 Pearson Education, Inc. All rights reserved.
101
Outline
fig05_15.c
(4 of 4 )
© 2007 Pearson Education, Inc. All rights reserved.
102
Fig. 5.16 | Set of recursive calls for fibonacci(3).
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.17
Writing programs that depend on the order of evaluation of the operands of operators other than &&, ||, ?:, and the comma (,) operator can lead to errors because compilers may not necessarily evaluate the operands in the order you expect.
103
© 2007 Pearson Education, Inc. All rights reserved.
Portability Tip 5.2
Programs that depend on the order of evaluation of the operands of operators other than &&, ||, ?:, and the comma (,) operator can function differently on systems with different compilers.
104
© 2007 Pearson Education, Inc. All rights reserved.
Performance Tip 5.4
Avoid Fibonacci-style recursive programs which result in an exponential “explosion” of calls.
105
© 2007 Pearson Education, Inc. All rights reserved.
5.16 Recursion vs. Iteration
106
© 2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 5.13
Any problem that can be solved recursively can also be solved iteratively (nonrecursively). A recursive approach is normally chosen in preference to an iterative approach when the recursive approach more naturally mirrors the problem and results in a program that is easier to understand and debug. Another reason to choose a recursive solution is that an iterative solution may not be apparent.
107
© 2007 Pearson Education, Inc. All rights reserved.
Performance Tip 5.5
Avoid using recursion in performance situations. Recursive calls take time and consume additional memory.
108
© 2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 5.18
Accidentally having a nonrecursive function call itself either directly, or indirectly through another function.
109
© 2007 Pearson Education, Inc. All rights reserved.
Performance Tip 5.6
Functionalizing programs in a neat, hierarchical manner promotes good software engineering. But it has a price. A heavily functionalized program—as compared to a monolithic (i.e., one-piece) program without functions—makes potentially large numbers of function calls, and these consume execution time on a computer’s processor(s). So, although monolithic programs may perform better, they are more difficult to program, test, debug, maintain, and evolve.
110
© 2007 Pearson Education, Inc. All rights reserved.
111
Fig. 5.17 | Recursion examples and exercises in the text. (Part 1 of 2.)
© 2007 Pearson Education, Inc. All rights reserved.
112
Fig. 5.17 | Recursion examples and exercises in the text. (Part 2 of 2.)
© 2007 Pearson Education, Inc. All rights reserved.