functions and interfacescs-2303, c-term 20101 functions and interfaces in c cs-2303, system...
Post on 19-Dec-2015
220 views
TRANSCRIPT
Functions and InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 2
Your First C Program
#include <stdio.h>
int main (void) {
printf(″Hello, World!\n″);
return 0;
}
Functions and InterfacesCS-2303, C-Term 2010 3
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 2010 4
So where is printf declared?
#include <stdio.h>
int main (void) {
printf(″Hello, World!\n″);
return 0;
}
Answer: in this file!
Functions and InterfacesCS-2303, C-Term 2010 5
#include <file.h>
• 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 2010 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 dependson it must be recompiled!
Functions and InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 12
Questions?
Write, compile, and execute this program in Lab session today and
tomorrow
Functions and InterfacesCS-2303, C-Term 2010 13
What happens to your program …
…after it is compiled, but before it can be run?
Functions and InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 15
Static Linking and LoadingPrintf.c
Printf.o
Librarygcc
ar
Linker
Memory
HelloWorld.c
gcc
HelloWorld.o
Loader
a.out(or file name ofyour command)
Functions and InterfacesCS-2303, C-Term 2010 16
Static Linking and Loading
Linker
Printf.c
Printf.o
Librarygcc
ar
Memory
HelloWorld.c
gcc
HelloWorld.o
Loader
a.out(or file name ofyour command)
Part of gcc
Functions and InterfacesCS-2303, C-Term 2010 17
Static Linking and Loading
Linker
Printf.c
Printf.o
Librarygcc
ar
Memory
HelloWorld.c
gcc
HelloWorld.o
Loader
a.out(or file name ofyour command)
Part of gcc
Part of operating system
Functions and InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 21
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 2010 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 InterfacesCS-2303, C-Term 2010 23
Textbook References
• Chapter 4 of K&R
• Chapter 5 of D&D
Functions and InterfacesCS-2303, C-Term 2010 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) // loge x
– log10(x) // log10 x
– sqrt(x) // x 0– pow(x, y) // xy
– ...
#include <stdio.h>– printf()– fprintf()– scanf()– sscanf()– ...
#include <string.h>– strcpy()– strcat()– strcmp()– strlen()– ...
Functions and InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 27
Functions in C
resultType functionName(type1 param1, type2 param2, …) {
…
body
…
}
• If no result, resultType should be void• Warning if not!
• If no parameters, use void between ()
Functions and InterfacesCS-2303, C-Term 2010 28
Functions in C
resultType functionName(type1 param1, type2 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 2010 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 InterfacesCS-2303, C-Term 2010 30
• 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;
Using Functions (continued)This is a parameter
This is an argumentThis is also an argument
Functions and InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 33
• 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;
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 2010 34
• 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;
Using Functions (continued)
Function f is executed and returns a value of type int
Result of f is added to dSum is assigned to N
Functions and InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 42
“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 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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 InterfacesCS-2303, C-Term 2010 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++;
}; // ifreturn rc;
} // GetNewItem
Functions and InterfacesCS-2303, C-Term 2010 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++;
}; // ifreturn 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 = totalprev + input, count = countprev + 1
Functions and InterfacesCS-2303, C-Term 2010 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