Functions and InterfacesCS-2303, C-Term 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)
Functions and InterfacesCS-2303, C-Term Your First C Program #include int main (void) { printf(″Hello, World!\n″); return 0; }
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term So where is printf declared? #include int main (void) { printf(″Hello, World!\n″); return 0; } Answer: in this file!
Functions and InterfacesCS-2303, C-Term #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
Functions and InterfacesCS-2303, C-Term #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!
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term Questions? Write, compile, and execute this program in Lab session today and tomorrow
Functions and InterfacesCS-2303, C-Term What happens to your program … …after it is compiled, but before it can be run?
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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)
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term Questions?
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term Textbook References Chapter 4 of K&R Chapter 5 of D&D
Functions and InterfacesCS-2303, C-Term 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() –...
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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!
Functions and InterfacesCS-2303, C-Term 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 ()
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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;
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term 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.”
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term Questions?
Functions and InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term Questions?
Functions and InterfacesCS-2303, C-Term “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
Functions and InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term 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
Functions and InterfacesCS-2303, C-Term 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 InterfacesCS-2303, C-Term Questions?