Introduction to Functions CS2301 System Programming for NonMajors

  • Slides: 35
Download presentation
Introduction to Functions CS-2301, System Programming for Non-Majors (Slides include materials from The C

Introduction to Functions CS-2301, System Programming for Non-Majors (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel) CS-2301, B-Term 2009 Introduction to Functions 1

Definition – Function • A fragment of code that accepts zero or more argument

Definition – Function • A fragment of code that accepts zero or more argument values, produces a result value, and has zero or more side effects. • A method of encapsulating a subset of a program or a system • To hide details • To be invoked from multiple places • To share with others CS-2301, B-Term 2009 Introduction to Functions 2

Functions – a big Topic • • Examples Function definition Function prototypes & Header

Functions – a big Topic • • Examples Function definition Function prototypes & Header files Pre- and post-conditions Scope and storage class Implementation of functions Recursive functions CS-2301, B-Term 2009 Introduction to Functions 3

Common Functions #include <math. h> – – – sin(x) // radians cos(x) // radians

Common Functions #include <math. h> – – – sin(x) // radians cos(x) // radians tan(x) // radians atan(x) atan 2(y, x) exp(x) // ex log(x) // loge x log 10(x) // log 10 x sqrt(x) // x 0 pow(x, y) // xy. . . CS-2301, B-Term 2009 #include <stdio. h> – – – printf() fprintf() scanf() sscanf(). . . #include <string. h> Introduction to Functions – – – strcpy() strcat() strcmp() strlen(). . . 4

Common Functions (continued) • In Kernighan & Ritchie – – – <assert. h> <stdarg.

Common Functions (continued) • In Kernighan & Ritchie – – – <assert. h> <stdarg. h> <time. h> <limits. h> <float. h> // for diagnostics, loop invariants, etc. // for parsing arguments // time of day and elapsed time // implementation dependent numbers. – <setjmp. h> // beyond scope of this course – <signal. h> // beyond scope of this course CS-2301, B-Term 2009 Introduction to Functions 5

Common Functions (continued) • See also the man pages of your system for things

Common Functions (continued) • See also the man pages of your system for things like • <pthread. h> • <socket. h> • . . . // 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! CS-2301, B-Term 2009 Introduction to Functions 6

Functions in C result. Type function. Name(type 1 param 1, type 2 param 2,

Functions in C result. Type function. Name(type 1 param 1, type 2 param 2, …) { … body … } • If no result, result. Type should be void • Warning if not! • If no parameters, use void between () CS-2301, B-Term 2009 Introduction to Functions 7

Functions in C result. Type function. Name(type 1 param 1, type 2 param 2,

Functions in C result. Type function. Name(type 1 param 1, type 2 param 2, …) { … ys a w l a o t e l y t body ds a o o h g t i s i w e It on m i t a c n n s u t f … gi n i w end a o sh t n e } // function. Name comm • If no result, result. Type should be void • Warning if not! • If no parameters, use void between () CS-2301, B-Term 2009 Introduction to Functions 8

Using Functions • Let int f(double x, int a) be (the beginning of) a

Using Functions • Let int f(double x, int a) be (the beginning of) a declaration of a function. • Then f(expr 1, expr 2) can be used in any expression where a value of type int can be used – e. g. , N = f(pi*pow(r, 2), b+c) + d; CS-2301, B-Term 2009 Introduction to Functions 9

Using Functions (continued) This is a parameter • Let int f(double x, int a)

Using Functions (continued) This is a parameter • Let int f(double x, int a) be (the beginning of) a declaration of a function. • Then f(expr 1, expr 2) can be used in any expression where a value of type int can be used – e. g. , N = f(pi*pow(r, 2), b+c) + d; This is also an This is an argument CS-2301, B-Term 2009 Introduction to Functions 10

Definitions • Parameter: – a declaration of an identifier within the '()' of a

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 CS-2301, B-Term 2009 Introduction to Functions 11

Using Functions (continued) • Let int f(double x, int a) be (the The is

Using Functions (continued) • Let int f(double x, int a) be (the The is e secof) ev firsbeginning on a declaration of a function. alu t aarg valu d a and ated nduam ate rgu ass , con sseingt e d, co men t ex ign n n x v e v p e d e e • Then pre 2) can be used in any ted troess 1, rtedexpr d to rf(expr par to d pairoanmi to i ssion o s a value am expression of type int can be nt ub ete where , le eter rx a , used – e. g. , N = f(pi*pow(r, 2), b+c) + d; CS-2301, B-Term 2009 Introduction to Functions 12

Using Functions (continued) • Let int f(double x, int a) be (the beginning of)

Using Functions (continued) • Let int f(double x, int a) be (the beginning of) a declaration of a function. • Then f(expr 1, expr 2) can be used in any expression where a value of type int can be used – e. g. , N = f(pi*pow(r, 2), b+c) + d; Function f is executed and Sum is assigned to N returns a value of type int CS-2301, B-Term 2009 Introduction to Functions Result of f is added to d 13

Questions? CS-2301, B-Term 2009 Introduction to Functions 14

Questions? CS-2301, B-Term 2009 Introduction to Functions 14

Function Definition • Every function definition has the form return-type function-name (parameter declarations) {

Function Definition • Every function definition has the form return-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 CS-2301, B-Term 2009 Introduction to Functions 15

Note • Functions in C do not allow other functions to be declared within

Note • Functions in C do not allow other functions to be declared within them • Like C++, Java • Unlike Algol, Pascal • All functions defined at “top level” of C programs • (Usually) visible to linker • Can be linked by any other program that knows the function prototype CS-2301, B-Term 2009 Introduction to Functions 16

Examples • double sin(double radians) { … } // sin • unsigned int strlen

Examples • double sin(double radians) { … } // sin • unsigned int strlen (char *s) { … } // strlen CS-2301, B-Term 2009 Introduction to Functions 17

Note on printf, etc. • int printf(char *s, . . . ) { body

Note on printf, etc. • int printf(char *s, . . . ) { body } // printf • In this function header, “…” is not a professor’s place-holder • (as often used in these slides) • …but an actual sequence of three dots (no spaces between) • Meaning: – the number and types of arguments is indeterminate • Use <stdarg. h> to extract the arguments CS-2301, B-Term 2009 Introduction to Functions 18

Questions? CS-2301, B-Term 2009 Introduction to Functions 19

Questions? CS-2301, B-Term 2009 Introduction to Functions 19

Function Prototypes • There are many, many situations in which a function must be

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 C program • In one or more completely separate C programs • This is actually the normal case! • Therefore, we need some way to declare a function separate from defining its body. • Called a Function Prototype CS-2301, B-Term 2009 Introduction to Functions 20

Function Prototypes (continued) • Definition: – a Function Prototype in C is a language

Function Prototypes (continued) • Definition: – a Function Prototype in C is 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 CS-2301, B-Term 2009 Introduction to Functions 21

Purposes of Function Prototype • So compiler knows how to compile calls to that

Purposes of Function Prototype • So compiler knows how to compile calls to that function, i. e. , – number and types of arguments – type of result • As part of a “contract” between developer and programmer who uses the function • As part of hiding details of how it works and exposing what it does. • A function serves as a “black box. ” CS-2301, B-Term 2009 Introduction to Functions 22

Header files • In applications with multiple C programs, function prototypes are typically provided

Header files • In applications with multiple C programs, function prototypes are typically provided in header files • I. e. , the ‘. h’ files that programmers include in their code • 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 CS-2301, B-Term 2009 Introduction to Functions 23

#include • #include <foo. h> • Search the system’s directories in order for a

#include • #include <foo. h> • Search the system’s directories in order for a file of the name foo. h • Directories can be added with ‘-I’ switch to gcc command – E. g. , gcc –I my. Project/include foo. c – Precedes system directories in search order • #include "foo. h" • Search the directory where the source program is found first, before -I and system directories CS-2301, B-Term 2009 Introduction to Functions 24

Typical C Programming Style • A lot of small C programs, rather than a

Typical C Programming Style • A lot of small C programs, rather than a few large 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 an organized way • Later in the term CS-2301, B-Term 2009 Introduction to Functions 25

Definition – Stub • A stub is a dummy implementation of a function with

Definition – Stub • 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 CS-2301, B-Term 2009 Introduction to Functions 26

Questions? CS-2301, B-Term 2009 Introduction to Functions 27

Questions? CS-2301, B-Term 2009 Introduction to Functions 27

“Contract” between Developer and User of a Function 1. Function Prototype 2. The pre-

“Contract” between Developer and User of a Function 1. Function Prototype 2. The pre- and post-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 function does CS-2301, B-Term 2009 Introduction to Functions 28

Definitions • Pre-condition: –a characterization or logical statement about • the values of the

Definitions • Pre-condition: –a characterization or logical statement about • the values of the parameters, and • values of relevant variables outside the function prior to calling the function • Post-condition: –a logical statement or characterization about • the result of the function in relation to the values of the parameters and pre-conditions, and • changes to values of variables outside the function after the function returns CS-2301, B-Term 2009 Introduction to Functions 29

Example 1 • double sin (double angle); – Pre: – angle is expressed in

Example 1 • double sin (double angle); – Pre: – angle is expressed in radians – Post: – result is the familiar sine of angle – Note: this function does not use or change any other variables CS-2301, B-Term 2009 Introduction to Functions 30

Example 2 • int printf (string, arg 1, arg 2, …) – Pre: –

Example 2 • int printf (string, arg 1, arg 2, …) – Pre: – string terminated with '' and containing conversion specifiers – Pre: – a buffer maintained by the file system contains zero or more unprinted characters from previous calls. – Post: – args are substituted for conversion codes in copy of string; 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: – result is number of characters added to buffer by printf CS-2301, B-Term 2009 Introduction to Functions 31

Example 3 float total = 0; int count = 0; int Get. New. Item(void)

Example 3 float total = 0; int count = 0; int Get. New. Item(void) { float input; int rc; printf("Enter next item: - "); if ((rc = scanf("%f", &input)) != EOF && (rc > 0)) { total += input; count++; }; // if return rc; } // Get. New. Item CS-2301, B-Term 2009 Introduction to Functions 32

Example 3 Pre: – total is sum of all previous inputs, or zero if

Example 3 Pre: – total is sum of all previous inputs, or zero if none Pre: – count is number of previous inputs, or zero if none float total = 0; int count = 0; int Get. Item(void) { float input; Post: – if valid input is received int rc; total = totalprev + input, . . . ; count = countprev + 1 if ((rc = scanf(“%f”, &input)) != EOF && (rc > 0)) { total += input; count++; }; // if return rc; } // Get. Item CS-2301, B-Term 2009 Introduction to Functions 33

Important • Pre- and post-conditions are analogous to loop invariants • I. e. ,

Important • Pre- and post-conditions are analogous to loop invariants • I. e. , they describe something about the data before and after a function is called and the relationship that the function preserves • Often are used together with loop invariants • … to show that loop invariant is preserved from one iteration to the next CS-2301, B-Term 2009 Introduction to Functions 34

Questions? CS-2301, B-Term 2009 Introduction to Functions 35

Questions? CS-2301, B-Term 2009 Introduction to Functions 35