Functions and Interfaces in C CS2303 System Programming

  • Slides: 49
Download presentation
Functions and Interfaces in C CS-2303, System Programming Concepts (Slides include materials from The

Functions and Interfaces in C CS-2303, System Programming Concepts (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-2303, C-Term 2010 Functions and Interfaces 1

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return 0; } CS-2303, C-Term 2010 Functions and Interfaces 2

Fundamental Rule in C • Every identifier must be declared before it can be

Fundamental Rule in C • Every identifier must be declared before it can be used in a program • Definition: – “identifier” • A sequence of letters, digits, and ‘_’ • Must begin with a letter or ‘_’ • Case is significant – Upper and lower case letters are different • Must not be a “reserved word” — see p. 192 of K&R • Definition: – “declare” • Introduce an identifier and the kind of entity it refers to • Optionally, define associated memory or program CS-2303, C-Term 2010 Functions and Interfaces 3

So where is printf declared? #include <stdio. h> Answer: in this file! int main

So where is printf declared? #include <stdio. h> Answer: in this file! int main (void) { printf(″Hello, World!n″); return 0; } CS-2303, C-Term 2010 Functions and Interfaces 4

#include <file. h> aka Header file • Logically: – • Equivalent to an interface

#include <file. h> aka Header file • Logically: – • Equivalent to an interface in Java • I. e. , where types and functions are declared • Physically: – • A file of C code that is copied into your program at compile time – By the C preprocessor • Spells out the contract of the interface between implementer and client CS-2303, C-Term 2010 Functions and Interfaces 5

#include <stdio. h> • Declares everything that your program needs to know about the

#include <stdio. h> • Declares everything that your program needs to know about the “standard I/O facilities” of C … • … and conceals everything that your program does not need to know about those same facilities • Doesn’t change very often CS-2303, C-Term 2010 Functions and Interfaces And when it does change, every program that depends on it must be recompiled! 6

Your First C Program #include <stdio. h> • Body of the function • Defines

Your First C Program #include <stdio. h> • Body of the function • Defines what the function “does” int main (void) { • Sequence of printf(″Hello, World!n″); statements return 0; • Each does a step of the function } • Enclosed in curly brackets { } • Indistinguishable from a compound statement CS-2303, C-Term 2010 Functions and Interfaces 7

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return 0; } • Call to another function • In this case, a function defined by the system • Prints some data on standard output CS-2303, C-Term 2010 Functions and Interfaces 8

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return 0; } • Argument to printf – a constant string • Enclosed in straight double quotes • Note the new-line character ′n′ at the end CS-2303, C-Term 2010 Functions and Interfaces 9

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return 0; } • A return statement • return is a reserved word in C • main should return zero if no error; non-zero if error CS-2303, C-Term 2010 Functions and Interfaces 10

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return

Your First C Program #include <stdio. h> int main (void) { printf(″Hello, World!n″); return 0; } • Note that statements typically end with semicolons • So compiler can tell where end of statement is CS-2303, C-Term 2010 Functions and Interfaces 11

Questions? Write, compile, and execute this program in Lab session today and tomorrow CS-2303,

Questions? Write, compile, and execute this program in Lab session today and tomorrow CS-2303, C-Term 2010 Functions and Interfaces 12

What happens to your program … …after it is compiled, but before it can

What happens to your program … …after it is compiled, but before it can be run? CS-2303, C-Term 2010 Functions and Interfaces 13

Example #include <stdio. h> • Symbol defined in your program and used elsewhere int

Example #include <stdio. h> • Symbol defined in your program and used elsewhere int main (void) { printf (″Hello, ″ ″ worldn″); return 0; • main • Symbol defined elsewhere and used by your program • printf } CS-2303, C-Term 2010 Functions and Interfaces 14

Static Linking and Loading Printf. c gcc Hello. World. c gcc Library Printf. o

Static Linking and Loading Printf. c gcc Hello. World. c gcc Library Printf. o ar Hello. World. o Linker a. out (or file name of your command) Loader Memory CS-2303, C-Term 2010 Functions and Interfaces 15

Static Linking and Loading Printf. c gcc Hello. World. c gcc Library Printf. o

Static Linking and Loading Printf. c gcc Hello. World. c gcc Library Printf. o ar Hello. World. o Linker Part of gcc a. out (or file name of your command) Loader Memory CS-2303, C-Term 2010 Functions and Interfaces 16

Static Linking and Loading Printf. c gcc Hello. World. c gcc Library Printf. o

Static Linking and Loading Printf. c gcc Hello. World. c gcc Library Printf. o ar Hello. World. o Linker Part of gcc a. out Part of operating system (or file name of your command) Loader Memory CS-2303, C-Term 2010 Functions and Interfaces 17

Compiling Your Program • gcc Hello. World. c • Compiles the program in Hello.

Compiling Your Program • gcc Hello. World. c • Compiles the program in Hello. World. c, links with any standard libraries, puts executable in a. out • You should find Hello. World. o in your directory • gcc –o hello_world Hello. World. c • Same as above, but names the executable file hello_world instead of a. out • gcc –lrt Hello. World. c • Searches library named rt. a for functions to link (in addition to standard libraries) CS-2303, C-Term 2010 Functions and Interfaces 18

Compiling Your Program (continued) • gcc foo. c bar. c help. c • Compiles

Compiling Your Program (continued) • gcc foo. c bar. c help. c • Compiles the programs foo. c, bar. c, and help. c, links with standard libraries, executable in a. out • You should find foo. o, bar. o, and help. o in your directory • gcc –o Lab 2 foo. c bar. c help. c • Same as above, but names the executable file Lab 2 • gcc –c foo. c bar. c help. c • Compiles foo. c, bar. c, and help. c to foo. o, bar. o, and help. o but does not link together • gcc –o Lab 2 foo. o bar. o help. o • Links together previously compiled foo. o, bar. o, help. o, stores result in Lab 2 CS-2303, C-Term 2010 Functions and Interfaces 19

Questions? CS-2303, C-Term 2010 Functions and Interfaces 20

Questions? CS-2303, C-Term 2010 Functions and Interfaces 20

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 function in C is equivalent to a method in Java, but without the surrounding class • 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-2303, C-Term 2010 Functions and Interfaces 21

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 rules and storage classes Implementation of functions Recursive functions CS-2303, C-Term 2010 Functions and Interfaces 22

Textbook References • Chapter 4 of K&R • Chapter 5 of D&D CS-2303, C-Term

Textbook References • Chapter 4 of K&R • Chapter 5 of D&D CS-2303, C-Term 2010 Functions and Interfaces 23

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

Common Functions in C #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-2303, C-Term 2010 #include <stdio. h> – – – printf() fprintf() scanf() sscanf(). . . #include <string. h> Functions and Interfaces – – – strcpy() strcat() strcmp() strlen(). . . 24

Common Functions (continued) • In K&R, also in D&D – – – <assert. h>

Common Functions (continued) • In K&R, also in D&D – – – <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-2303, C-Term 2010 Functions and Interfaces 25

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 in C! CS-2303, C-Term 2010 Functions and Interfaces 26

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-2303, C-Term 2010 Functions and Interfaces 27

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-2303, C-Term 2010 Functions and Interfaces 28

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-2303, C-Term 2010 Functions and Interfaces 29

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-2303, C-Term 2010 Functions and Interfaces 30

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 by the caller 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-2303, C-Term 2010 Functions and Interfaces 31

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 by the caller to the value of the corresponding argument. Note: to parameters withinathe Argument: – an Changes expression passed when function do not propagate back to caller! function is called; becomes the initial value of the corresponding parameter All parameters in C are “call by value. ” CS-2303, C-Term 2010 Functions and Interfaces 32

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-2303, C-Term 2010 Functions and Interfaces 33

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-2303, C-Term 2010 Functions and Interfaces Result of f is added to d 34

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 • Can “see” anything declared previously in same program (or in an included interface) CS-2303, C-Term 2010 Functions and Interfaces 35

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

Note on printf parameters • int printf(char *s, . . . ) { body } // printf • In this function header, “…” is not a professor’s shorthand • (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-2303, C-Term 2010 Functions and Interfaces 36

Questions? CS-2303, C-Term 2010 Functions and Interfaces 37

Questions? CS-2303, C-Term 2010 Functions and Interfaces 37

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-2303, C-Term 2010 Functions and Interfaces 38

Function Prototypes (continued) aka function header • Definition: – a Function Prototype in C

Function Prototypes (continued) aka function header • 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 • Essentially, the method of a Java interface. CS-2303, C-Term 2010 Functions and Interfaces 39

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-2303, C-Term 2010 Functions and Interfaces 40

Questions? CS-2303, C-Term 2010 Functions and Interfaces 41

Questions? CS-2303, C-Term 2010 Functions and Interfaces 41

“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-2303, C-Term 2010 Functions and Interfaces 42

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-2303, C-Term 2010 Functions and Interfaces 43

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-2303, C-Term 2010 Functions and Interfaces 44

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-2303, C-Term 2010 Functions and Interfaces 45

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

Example 3 float total = 0; int count = 0; int Get. 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-2303, C-Term 2010 Functions and Interfaces 46

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-2303, C-Term 2010 Functions and Interfaces 47

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-2303, C-Term 2010 Functions and Interfaces 48

Questions? CS-2303, C-Term 2010 Functions and Interfaces 49

Questions? CS-2303, C-Term 2010 Functions and Interfaces 49