Upload
hadieu
View
219
Download
0
Embed Size (px)
Citation preview
7/30/2019 Week 2, Introduction to Functions
1/35
Introduction to FunctionsCS-2301, B-Term 2009 1
Introduction to Functions
CS-2301, System Programming
for Non-Majors
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and
from C: How to Program, 5th and 6th editions, by Deitel and Deitel)
7/30/2019 Week 2, Introduction to Functions
2/35
Introduction to FunctionsCS-2301, B-Term 2009 2
DefinitionFunction
A fragment of code that accepts zero or
more argument values, produces a result
value, and has zero or more side effects.
A method ofencapsulating a subset of a
program or a system
To hide details
To be invoked from multiple places
To share with others
7/30/2019 Week 2, Introduction to Functions
3/35
Introduction to FunctionsCS-2301, B-Term 2009 3
Functionsa big Topic
Examples
Function definition
Function prototypes & Header files Pre- and post-conditions
Scope and storage class
Implementation of functions Recursive functions
7/30/2019 Week 2, Introduction to Functions
4/35
Introduction to FunctionsCS-2301, B-Term 2009 4
Common Functions
#include
sin(x) // radians
cos(x) // radians
tan(x) // radians
atan(x)
atan2(y,x) exp(x) //ex
log(x) // logex
log10(x) // log10x sqrt(x) //x 0
pow(x, y) //xy
...
#include
printf()
fprintf()
scanf()
sscanf()
...
#include
strcpy()
strcat() strcmp()
strlen()
...
7/30/2019 Week 2, Introduction to Functions
5/35
Introduction to FunctionsCS-2301, B-Term 2009 5
Common Functions (continued)
In Kernighan & Ritchie// for diagnostics, loop invariants, etc.
// for parsing arguments
// time of day and elapsed time// implementation dependent numbers
// implementation dependent numbers.
// beyond scope of this course// beyond scope of this course
7/30/2019 Week 2, Introduction to Functions
6/35
Introduction to FunctionsCS-2301, B-Term 2009 6
Common Functions (continued)
See also theman pages of your system forthings like
// concurrent execution
// network communications... // many, many other facilities
Fundamental Rule: if there is a chance that
someone else had same problem as you, there is probably a package of functions
to solve it!
7/30/2019 Week 2, Introduction to Functions
7/35
Introduction to FunctionsCS-2301, B-Term 2009 7
Functions in C
resultType functionName(type1param1, type2
param2, ) {
body
}
If no result, resultType should be void Warning if not!
If no parameters, use voidbetween ()
7/30/2019 Week 2, Introduction to Functions
8/35
Introduction to FunctionsCS-2301, B-Term 2009 8
Functions in C
resultType functionName(type1param1, type2
param2, ) {
body
} // functionName
If no result, resultType should be void Warning if not!
If no parameters, use voidbetween ()
7/30/2019 Week 2, Introduction to Functions
9/35
Introduction to FunctionsCS-2301, B-Term 2009 9
Using Functions
Let int f(double x, int a)be (the
beginning of) a declaration of a function.
Then f(expr1, expr2) can be used in anyexpression where a value of type int can be
usede.g.,
N = f(pi*pow(r,2), b+c) + d;
7/30/2019 Week 2, Introduction to Functions
10/35
Introduction to FunctionsCS-2301, B-Term 2009 10
Let int f(double x, int a)be (the
beginning of) a declaration of a function.
Then f(expr1, expr2) can be used in anyexpression where a value of type int can be
usede.g.,
N = f(pi*pow(r,2), b+c) + d;
Using Functions (continued)This is aparameter
This is an argumentThis is also an
argument
7/30/2019 Week 2, Introduction to Functions
11/35
Introduction to FunctionsCS-2301, B-Term 2009 11
Definitions
Parameter:
a declaration of an identifier
within the '()' of a function declaration
Used within the body of the function as a variable of
that function Initialized to the value of the corresponding
argument.
Argument:an expression passed when a
function is called; becomes the initial value
of the corresponding parameter
7/30/2019 Week 2, Introduction to Functions
12/35
Introduction to FunctionsCS-2301, B-Term 2009 12
Let int f(double x, int a)be (the
beginning of) a declaration of a function.
Then f(expr1, expr2) can be used in anyexpression where a value of type int can be
usede.g.,
N = f(pi*pow(r,2), b+c) + d;
Using Functions (continued)
7/30/2019 Week 2, Introduction to Functions
13/35
Introduction to FunctionsCS-2301, B-Term 2009 13
Let int f(double x, int a)be (the
beginning of) a declaration of a function.
Then f(expr1, expr2) can be used in anyexpression where a value of type int can be
usede.g.,
N = f(pi*pow(r,2), b+c) + d;
Using Functions (continued)
Function f is executed and
returns a value of type intResult off is added to dSum is assigned toN
7/30/2019 Week 2, Introduction to Functions
14/35
Introduction to FunctionsCS-2301, B-Term 2009 14
Questions?
7/30/2019 Week 2, Introduction to Functions
15/35
Introduction to FunctionsCS-2301, B-Term 2009 15
Function Definition
Every function definition has the formreturn-type function-name (parameter declarations){
definitions and statements
}
See top of page 70 in Kernighan & Ritchie
For practical purposes, code between {}
(inclusive) is a compound statement
7/30/2019 Week 2, Introduction to Functions
16/35
Introduction to FunctionsCS-2301, B-Term 2009 16
Note
Functions in Cdo notallow other functionsto be declared within them
Like C++, Java
Unlike Algol, Pascal
All functions defined at top level ofCprograms
(Usually) visible to linker Can be linked by any other program that knows the
function prototype
7/30/2019 Week 2, Introduction to Functions
17/35
Introduction to FunctionsCS-2301, B-Term 2009 17
Examples
double sin(double radians) {
} // sin
unsigned int strlen (char *s) {
} // strlen
7/30/2019 Week 2, Introduction to Functions
18/35
Introduction to FunctionsCS-2301, B-Term 2009 18
Note onprintf, etc.
int printf(char *s, ...) {
body
} // printf
In this function header, is nota professorsplace-holder
(as often used in these slides)
but an actual sequence of three dots (no spacesbetween)
Meaning:the number and types of arguments is indeterminate
Useto extract the arguments
7/30/2019 Week 2, Introduction to Functions
19/35
Introduction to FunctionsCS-2301, B-Term 2009 19
Questions?
7/30/2019 Week 2, Introduction to Functions
20/35
Introduction to FunctionsCS-2301, B-Term 2009 20
Function Prototypes
There are many, many situations in which a
function must be used separate from where
it is defined
before its definition in the same Cprogram
In one or more completely separate Cprograms
This is actually the normal case!
Therefore, we need some way to declare afunction separate from defining its body.
Called a Function Prototype
7/30/2019 Week 2, Introduction to Functions
21/35
Introduction to FunctionsCS-2301, B-Term 2009 21
Function Prototypes (continued)
Definition:a Function Prototype in Cis a
language construct of the form:
return-type function-name(parameter declarations
) ;
I.e., exactly like a function definition, except with a
';' instead of a body in curly brackets
7/30/2019 Week 2, Introduction to Functions
22/35
Introduction to FunctionsCS-2301, B-Term 2009 22
Purposes of Function Prototype
So compiler knows how to compile calls to thatfunction, i.e., number and types of arguments
type of result
As part of a contract between developer andprogrammer who uses the function
As part of hiding details ofhow it works and
exposing whatit does.
A function serves as a black box.
7/30/2019 Week 2, Introduction to Functions
23/35
Introduction to FunctionsCS-2301, B-Term 2009 23
Header files
In applications with multiple Cprograms,
function prototypes are typically provided
in header files
I.e., the .h files that programmers include in theircode
Grouped by related functions and features To make it easier for developers to understand
To make it easier for team development
To make a package that can be used by someone
else
7/30/2019 Week 2, Introduction to Functions
24/35
Introduction to FunctionsCS-2301, B-Term 2009 24
#include
#include
Search the systems directories in orderfor a file of
the name foo.h
Directories can be added with -I switch to gcc
command
E.g., gcc I myProject/include foo.c
Precedes system directories in search order
#include "foo.h"
Search the directory where the source program isfound first, before-I and system directories
7/30/2019 Week 2, Introduction to Functions
25/35
Introduction to FunctionsCS-2301, B-Term 2009 25
Typical CProgramming Style
A lot of small Cprograms, rather than a fewlarge ones
Each .c file contains closely related functions
Usually a small number of functions
Header files to tie them together
Makefiles to build or rebuild them in anorganized way
Later in the term
7/30/2019 Week 2, Introduction to Functions
26/35
Introduction to FunctionsCS-2301, B-Term 2009 26
DefinitionStub
A stub is a dummy implementation of a
function with an empty body
A placeholder while building (other parts
of) a program
So that it compiles correctly
Fill in one-stub at a time Compile and test if possible
7/30/2019 Week 2, Introduction to Functions
27/35
Introduction to FunctionsCS-2301, B-Term 2009 27
Questions?
7/30/2019 Week 2, Introduction to Functions
28/35
Introduction to FunctionsCS-2301, B-Term 2009 28
Contract between Developer and User of a
Function
1. Function Prototype
2. Thepre- andpost-conditions
I.e., assertions about what is true before the
function is called and what is true after it
returns.
A logical way of explaining what the functiondoes
7/30/2019 Week 2, Introduction to Functions
29/35
Introduction to FunctionsCS-2301, B-Term 2009 29
Definitions
Pre-condition:
a characterization or logicalstatement about
the values of the parameters, and
values of relevant variables outside the function
prior to calling the function
Post-condition:a logical statement orcharacterization about
the resultof the function in relation to the values of theparameters and pre-conditions, and
changes to values of variables outside the function
after the function returns
7/30/2019 Week 2, Introduction to Functions
30/35
Introduction to FunctionsCS-2301, B-Term 2009 30
Example 1
double sin (double angle);
Pre:angle is expressed in radians
Post:result is the familiar sine ofangle
Note: this function does not use or change anyother variables
7/30/2019 Week 2, Introduction to Functions
31/35
Introduction to FunctionsCS-2301, B-Term 2009 31
Example 2
int printf (string, arg1, arg2, )
Pre:string terminated with '\0' and containing
conversion specifiers
Pre:a buffermaintained by the file system contains
zero or more unprinted characters from previous calls.
Post:args are substituted for conversion codes in
copy ofstring; resulting string is added to buffer
Post:if'\n'is anywhere in buffer, line is printed
up to '\n'; printed characters are cleared from buffer
Post:resultis number of characters added to buffer byprintf
7/30/2019 Week 2, Introduction to Functions
32/35
Introduction to FunctionsCS-2301, B-Term 2009 32
Example 3
float total = 0;int count = 0;
int GetNewItem(void) {float input;
int rc;printf("Enter next item:- ");
if ((rc = scanf("%f", &input)) != EOF
&& (rc > 0)) {total += input;count++;
}; // if
return rc;
} // GetNewItem
7/30/2019 Week 2, Introduction to Functions
33/35
Introduction to FunctionsCS-2301, B-Term 2009 33
Example 3
float total = 0;int count = 0;
int GetItem(void) {float input;
int rc;...;
if ((rc = scanf(%f, &input)) != EOF
&& (rc > 0)) {total += input;count++;
}; // if
return rc;
} // GetItem
Pre: total is sum of allprevious inputs, or zero if none
Pre:count is number of
previous inputs, or zero if none
Post:if valid input is received
total = totalprev + input,count = countprev + 1
7/30/2019 Week 2, Introduction to Functions
34/35
Introduction to FunctionsCS-2301, B-Term 2009 34
Important
Pre- andpost-conditions are analogous to
loop invariants
I.e., they describe something about the data before
and after a function is called and the relationshipthat the function preserves
Often are used together with loop invariants to show that loop invariant is preserved from one
iteration to the next
7/30/2019 Week 2, Introduction to Functions
35/35
Introduction to FunctionsCS-2301, B-Term 2009 35
Questions?