1 / 49

Functions and Interfaces in C

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). Your First C Program. #include <stdio.h>

abra
Download Presentation

Functions and Interfaces in C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

  3. Fundamental Rule in C Functions and Interfaces • 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. So where is printf declared? #include <stdio.h> int main (void) { printf(″Hello, World!\n″); return 0; } Answer: in this file! Functions and Interfaces

  5. #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 Functions and Interfaces

  6. #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 And when it does change,every program that depends on it must be recompiled! Functions and Interfaces

  7. Your First C Program #include <stdio.h> 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 Functions and Interfaces

  8. 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 Functions and Interfaces

  9. 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 Functions and Interfaces

  10. 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 Functions and Interfaces

  11. 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 Functions and Interfaces

  12. Questions? Write, compile, and execute this program in Lab session today and tomorrow Functions and Interfaces

  13. What happens to your program … …after it is compiled, but before it can be run? Functions and Interfaces

  14. Example #include <stdio.h> 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 Functions and Interfaces

  15. Static Linking and Loading Printf.c HelloWorld.c gcc Library gcc Printf.o ar HelloWorld.o Linker a.out(or file name ofyour command) Loader Memory Functions and Interfaces

  16. Static Linking and Loading Printf.c HelloWorld.c gcc Library gcc Printf.o ar HelloWorld.o Linker Part of gcc a.out(or file name ofyour command) Loader Memory Functions and Interfaces

  17. Static Linking and Loading Printf.c HelloWorld.c gcc Library gcc Printf.o ar HelloWorld.o Linker Part of gcc a.out(or file name ofyour command) Part of operating system Loader Memory Functions and Interfaces

  18. 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) Functions and Interfaces

  19. 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 Functions and Interfaces

  20. Questions? Functions and Interfaces

  21. Definition – Function A fragment of code that accepts zero or more argument values, produces a resultvalue, 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 Functions and Interfaces

  22. 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 Functions and Interfaces

  23. Textbook References • Chapter 4 of K&R • Chapter 5 of D&D Functions and Interfaces

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

  25. Common Functions (continued) In K&R, also in D&D <assert.h> // for diagnostics, loop invariants, etc. <stdarg.h> // for parsing arguments <time.h> // time of day and elapsed time <limits.h> // implementation dependent numbers <float.h> // implementation dependent numbers. <setjmp.h>// beyond scope of this course <signal.h>// beyond scope of this course Functions and Interfaces

  26. Common Functions (continued) See also the man pages of your system for things like <pthread.h> // concurrent execution <socket.h> // 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! Functions and Interfaces

  27. Functions in C resultType functionName(type1param1, type2param2, …) { … body … } If no result, resultType should be void Warning if not! If no parameters, use void between () Functions and Interfaces

  28. Functions in C resultType functionName(type1param1, type2param2, …) { … 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 Functions and Interfaces

  29. 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 any expression where a value of type int can be used – e.g., N = f(pi*pow(r,2), b+c) + d; Functions and Interfaces

  30. This is a parameter This is also an argument This is an argument Using Functions (continued) • Let int f(double x, int a) be (the beginning of) a declaration of a function. • Then f(expr1, expr2) 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; Functions and Interfaces

  31. 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 Functions and Interfaces

  32. 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 thefunction do not propagate back to caller! All parameters in C are “call by value.” Functions and Interfaces

  33. The second argument expression is evaluated, converted to int, and assigned to parameter a The first argument expression is evaluated, converted to double, and assigned to parameter x Using Functions (continued) • Let int f(double x, int a) be (the beginning of) a declaration of a function. • Then f(expr1, expr2) 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; Functions and Interfaces

  34. Function f is executed and returns a value of type int Result of f is added to d Sum is assigned to N Using Functions (continued) • Let int f(double x, int a) be (the beginning of) a declaration of a function. • Then f(expr1, expr2) 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; Functions and Interfaces

  35. 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) Functions and Interfaces

  36. 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 Functions and Interfaces

  37. Questions? Functions and Interfaces

  38. 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 Functions and Interfaces

  39. 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 Functions and Interfaces

  40. 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.” Functions and Interfaces

  41. Questions? Functions and Interfaces

  42. “Contract” between Developer and User of a Function Function Prototype 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 Functions and Interfaces

  43. 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 Functions and Interfaces

  44. 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 Functions and Interfaces

  45. Example 2 int printf (string, arg1, arg2, …) 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 Functions and Interfaces

  46. 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 Functions and Interfaces

  47. 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 receivedtotal = totalprev + input, count = countprev + 1 Functions and Interfaces

  48. 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 Functions and Interfaces

  49. Questions? Functions and Interfaces

More Related