Announcements • P5 due on Thursday • FINAL EXAM Tuesday August 10, 8AM, Olin 155 • Review sessions on Thursday and Friday • Final grades posted next Tuesday night/Wednesday morning. See me Wednesday, if you have questions, as I’m leaving town Wednesday night! CS 100 Lecture 21 1 Today’s Topics • • • • • C -- another programming language Goal: acquire a basic reading knowledge of C control structures program organization Standard Reference: The C Programming Language by Kernighan and Ritchie -- fairly terse CS 100 Lecture 21 2 Java vs. C Java Advantages • Direct support of classes, objects, and other tools for effectively organizing medium-to-large programs. • Extensive standard class libraries (for I/O, GUIs, networking, etc.). • Automatic memory management (garbage collection). • Portable (write once, run everywhere), because of the Java Virtual Machine. • Used for writing Applets for the world wide web CS 100 Lecture 21 3 Java vs. C Java Disadvantages • Portability, garbage collection, and other features impose execution time and space overhead. • Java runtime environment keeps Java program at a distance from the underlying machine. • Therefore, Java programs are much slower than C programs. CS 100 Lecture 21 4 Java vs. C C Advantages • Data types and constructs are close to those provided by the underlying hardware (microprocessor), so: • Good for writing programs that squeeze maximum performance from hardware. • Possible to have absolute control over machine resources --good for writing software that directly manipulates hardware devices. C is often thought of as a high-level assembly language. CS 100 Lecture 21 5 Java vs. C C Disadvantages • Not objected oriented (but C++ is) • No garbage collection. Programmer must manage the allocation and freeing of storage. This is highly prone to error. • Care needed to write programs that are portable. • As will be seen, programmer must manage “pointers” or references themselves, an extremely confusing and error-prone issue for many. CS 100 Lecture 21 6 Basic C Data types • Standard types similar to those in Java – int, long (integers) – float, double (floating point) – char (characters, normally ASCII) • No type boolean – 0 represents false (like Matlab) – non-0 represents true – relations (<. <=, ==, !=, >= >) and logical operations (!, &&, ||) yield 0 of false, 1 if true • Size of arithmetic types depends on machine/compiler. Examples: – int: usually 16 or 32 bits – long: at least as many bits as int, usually 32, sometimes 64. • Need to be careful if you want portable code. CS 100 Lecture 21 7 Basic C Statements • Assignment as in C: – variable = expression ; • Loops and conditionals just like in Java. – if (condition) if (condition) statement statement else statement – while (condition) statement – for (initialize; test; step) statement CS 100 Lecture 21 8 Contrast with Java on declaration locations: • Curly braces used to group statements, as in Java. But declarations cannot appear in a block, only in a method body. For example, the following is not legal C: if (x < y) {int tmp= x; x= y; y= tmp;} CS 100 Lecture 21 9 C Functions • C program is collection of functions • No classes, so function declarations appear freely in source code • No explicit public/private distinction • Example: /* Yield maximum of x and y */ int max (int x, int y) { if (x >= y) return x; else return y;} CS 100 Lecture 21 10 C Procedures • In C, a procedure is a function with return type void /*Print n lines of stars; line i, for 1<= i <= n, has i stars on it */ void print_stars (int n) { int j, k; for (k= 1; k <= n; k++) { /* Print line k, with k stars */ for (j= 1; j <= k; j++) printf(“*”); printf(“\n”); } } CS 100 Lecture 21 11 Source files (.c files) • C function definitions are placed in source files that have names ending in “.c”. • All functions normally may be accessed (called) by any other function in any file. • A function definition may be preceded by “static” to restrict access so that it may be called only by other functions defined in the same file. • External (“global”) variables may be defined in a .c file outside any function. – External variables are created when program execution begins; – they retain their values until execution of the program terminates. – External variables may also be defined static in order to restrict access to them to the file containing the variable definition. CS 100 Lecture 21 12 Source files (.h files) • Every function (and external variable) must be defined exactly once by giving a full definition in some .c source file. • A function (or external variable) may be called (or referenced) in other files provided that there is a declaration of the function (or external variable) in the other files. • The declaration of a function gives the function name and parameters, but not the function body. Example: int max(int x, int y); • Related declarations are often grouped in header files (name ending in “.h”). The declarations in a head file xyz.h can be incorporated in another file by the directive – #include “xyz.h” • or – #include <xyz.h.> CS 100 (for user files) (for standard C libraries) Lecture 21 13 Example: math library • File math.h contains declarations of the standard C math library routines: – – – – double sqrt (double x); double sin (double x); double cos (double x); etc. … • A client program can access the definitions using the appropriate include directive: #include <math.h> /* yield twice the square root of x */ double sqrt2 (double x) { return 2 * sqrt(x); } CS 100 Lecture 21 14 Standard Output • The library <stdio.h> includes basic routines to – read formatted data from the standard input (usually the keyboard) and – print on the standard output (usually a window on the monitor). • The basic output routine is printf. • A call to printf has one or more arguments. – The first is the “format string”, which contains literal text to be printed interspersed with formatting instructions for printing the remaining arguments. CS 100 Lecture 21 15 Example with printf #include <stdio.h> /* Print a table of Fahenehit-Celsius values from 0 to 300 in increments of 20 */ void main (void) { int d; printf(“Fahrenheit Celsius\n”); for (d= 0; d <= 300; d= d+20) printf(“%3d %6.1f\n”, d, (5.0/9.0) * (d-32) ); } CS 100 Lecture 21 16 Output of previous CS 100 Lecture 21 17 Parameters and Arguments • As in Java, the same four steps apply on a function call as on a method invocation • Example: Consider execution of #include <stdio.h> void f (int x, int y) { int tmp; tmp= x; x= y; y= tmp; } void main(void) { int j= 17; int k= 42; f(j, k); printf(“j= %d, k= %d\n”, j, k); } CS 100 Lecture 21 18 Pointers and References In Java, one can’t write a procedure to swap the values of two int variables x and y. The following method and call does not change x and y: public void notaSwap(int p1, int p2) {int t= p1; p1= p2; p2= t;} int x= 5; int y= 6; notaSwap(x,y); But one can change the values of fields of a class: public class Coord {int x; int y;} // Swap x fields of p1 and p2 public static void Swap(Coord p1, Coord p2) {int t= p1.x; p1.x= p1.y; p1.y= t;} Swap(p1, p2); CS 100 Lecture 21 19 Pointers in C C provides operator & to create a pointer to a variable int x= 5; p x 5 int & p= &x; int & y; The type of y is “int &”, read as “address of int) C provides operator a “dereferencing” operator If p is a pointer to an int variable, then * is the variable. * p = * p + 1; p int * x; CS 100 The type of x is “int *”, read asx “pointer to int” Lecture 21 6 20 Swap two integers void swap(int * x, int * y) { int tmp; tmp= * x; *x= *y; *y= tmp; } The parameters are no long of type int, but instead “point to int”. CS 100 Lecture 21 21 Standard Input • Function scanf in library <stdio.h> reads from the standard input device and deciphers the input characters according to the format string given as the first argument of a call. • The remaining arguments of a call to scanf are pointers to variables where the input values should be stored. • As with printf, C compilers generally can’t (or don’t) check that the types of the variables match the format codes in the format string. • A mismatch, usually a mistake, can lead to mysteriously scrambled bytes in memory or a program or machine crash. CS 100 Lecture 21 22 stdin Example void main(void) { int j, k; printf(“Please type in two integers”); // read integers into j and k. scanf(“%d %d”, &j, &k); printf(“the larger of the two is\n %d”, max(j,k)); Note that scanf f requires pointers to variables as arguments! CS 100 Lecture 21 23