Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions and InterfacesCS-2303, C-Term 20101 Functions and Interfaces in C CS-2303, System Programming Concepts (Slides include materials from The C Programming.

Similar presentations


Presentation on theme: "Functions and InterfacesCS-2303, C-Term 20101 Functions and Interfaces in C CS-2303, System Programming Concepts (Slides include materials from The C Programming."— Presentation transcript:

1 Functions and InterfacesCS-2303, C-Term 20101 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)

2 Functions and InterfacesCS-2303, C-Term 20102 Your First C Program #include int main (void) { printf(″Hello, World!\n″); return 0; }

3 Functions and InterfacesCS-2303, C-Term 20103 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

4 Functions and InterfacesCS-2303, C-Term 20104 So where is printf declared? #include int main (void) { printf(″Hello, World!\n″); return 0; } Answer: in this file!

5 Functions and InterfacesCS-2303, C-Term 20105 #include 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 aka Header file

6 Functions and InterfacesCS-2303, C-Term 20106 #include 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 And when it does change, every program that depends on it must be recompiled!

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

8 Functions and InterfacesCS-2303, C-Term 20108 Your First C Program #include 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

9 Functions and InterfacesCS-2303, C-Term 20109 Your First C Program #include 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

10 Functions and InterfacesCS-2303, C-Term 201010 Your First C Program #include 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

11 Functions and InterfacesCS-2303, C-Term 201011 Your First C Program #include 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

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

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

14 Functions and InterfacesCS-2303, C-Term 201014 Example #include int main (void) { printf (″Hello,″ ″ world\n″); return 0; } Symbol defined in your program and used elsewhere main Symbol defined elsewhere and used by your program printf

15 Functions and InterfacesCS-2303, C-Term 201015 Static Linking and Loading Printf.c Printf.o Library gcc ar Linker Memory HelloWorld.c gcc HelloWorld.o Loader a.out (or file name of your command)

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

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

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

19 Functions and InterfacesCS-2303, C-Term 201019 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 Lab2 foo.c bar.c help.c Same as above, but names the executable file Lab2 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 Lab2 foo.o bar.o help.o Links together previously compiled foo.o, bar.o, help.o, stores result in Lab2

20 Functions and InterfacesCS-2303, C-Term 201020 Questions?

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

22 Functions and InterfacesCS-2303, C-Term 201022 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

23 Functions and InterfacesCS-2303, C-Term 201023 Textbook References Chapter 4 of K&R Chapter 5 of D&D

24 Functions and InterfacesCS-2303, C-Term 201024 Common Functions in C #include –sin(x) // radians –cos(x) // radians –tan(x) // radians –atan(x) –atan2(y,x) –exp(x) // e x –log(x) // log e x –log10(x) // log 10 x –sqrt(x) // x  0 –pow(x, y) // x y –... #include –printf() –fprintf() –scanf() –sscanf() –... #include –strcpy() –strcat() –strcmp() –strlen() –...

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

26 Functions and InterfacesCS-2303, C-Term 201026 Common Functions (continued) See also the man pages of your system for things 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 in C!

27 Functions and InterfacesCS-2303, C-Term 201027 Functions in C resultType functionName( type 1 param1, type 2 param2, …) { … body … } If no result, resultType should be void Warning if not! If no parameters, use void between ()

28 Functions and InterfacesCS-2303, C-Term 201028 Functions in C resultType functionName( type 1 param1, type 2 param2, …) { … body … }// functionName If no result, resultType should be void Warning if not! If no parameters, use void between () It is good style to always end a function with a comment showing its name

29 Functions and InterfacesCS-2303, C-Term 201029 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;

30 Functions and InterfacesCS-2303, C-Term 201030 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; Using Functions (continued) This is a parameter This is an argument This is also an argument

31 Functions and InterfacesCS-2303, C-Term 201031 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

32 Functions and InterfacesCS-2303, C-Term 201032 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 Note: Changes to parameters within the function do not propagate back to caller! All parameters in C are “call by value.”

33 Functions and InterfacesCS-2303, C-Term 201033 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; Using Functions (continued) The first argument expression is evaluated, converted to double, and assigned to parameter x The second argument expression is evaluated, converted to int, and assigned to parameter a

34 Functions and InterfacesCS-2303, C-Term 201034 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; Using Functions (continued) Function f is executed and returns a value of type int Result of f is added to d Sum is assigned to N

35 Functions and InterfacesCS-2303, C-Term 201035 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)

36 Functions and InterfacesCS-2303, C-Term 201036 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 to extract the arguments

37 Functions and InterfacesCS-2303, C-Term 201037 Questions?

38 Functions and InterfacesCS-2303, C-Term 201038 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

39 Functions and InterfacesCS-2303, C-Term 201039 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 Essentially, the method of a Java interface. aka function header

40 Functions and InterfacesCS-2303, C-Term 201040 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.”

41 Functions and InterfacesCS-2303, C-Term 201041 Questions?

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

43 Functions and InterfacesCS-2303, C-Term 201043 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

44 Functions and InterfacesCS-2303, C-Term 201044 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

45 Functions and InterfacesCS-2303, C-Term 201045 Example 2 int printf (string, arg 1, arg 2, …) –Pre:– string terminated with '\0' 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

46 Functions and InterfacesCS-2303, C-Term 201046 Example 3 float total = 0; int count = 0; int GetItem(void) { float input; int rc; printf("Enter next item:- "); if ((rc = scanf("%f", &input)) != EOF && (rc > 0)) { total += input; count++; };// if return rc; }// GetNewItem

47 Functions and InterfacesCS-2303, C-Term 201047 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 all previous inputs, or zero if none Pre:– count is number of previous inputs, or zero if none Post:– if valid input is received total = total prev + input, count = count prev + 1

48 Functions and InterfacesCS-2303, C-Term 201048 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

49 Functions and InterfacesCS-2303, C-Term 201049 Questions?


Download ppt "Functions and InterfacesCS-2303, C-Term 20101 Functions and Interfaces in C CS-2303, System Programming Concepts (Slides include materials from The C Programming."

Similar presentations


Ads by Google