Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:

Similar presentations


Presentation on theme: "CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:"— Presentation transcript:

1 CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts: Basic C control structures, data, I/O Program organization Pointers and parameters Reference: The standard reference is The C Programming Language by Kernighan & Ritchie (2nd ed, 1988). But this is written for experienced programmers and can be quite terse for beginners.

2 CS100A, Fall 1997, Lectures 222 Java vs C Java advantages: Direct support of classes, objects, and other tools for effectively organizing medium to large programs. Extensive standard class libraries (GUI, network programming, etc.). Automatic memory management (garbage collection). Portable (write once, run everywhere). But: Portability, garbage collection, and other features impose execution time and space overhead. Java runtime environment keeps Java programs at a distance from the underlying machine.

3 CS100A, Fall 1997, Lectures 223 Java vs C (cont.) C advantages: Data types and constructs are very close to those provided by the underlying hardware (microprocessor), therefore, … 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. But: Limited facilities for organizing software (no classes, objects). No garbage collection — must be done by programmer and is highly prone to errors. Care needed to write programs that are portable — i.e., that don’t depend on a particular processor or compiler.

4 CS100A, Fall 1997, Lectures 224 Basic C Data Types Standard types are similar to Java: –int, long (integers) –float, double (floating-point) –char (characters, normally ASCII) But: No boolean type; use int instead. –0 taken to be false –non-0 taken to be true –relations ( =, >) and logical operations (!, &&, ||) yield 0 if false, 1 if true Actual 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.

5 CS100A, Fall 1997, Lectures 225 Basic C Control Structures Loops and conditionals look just like Java. if (condition) statement; else statement; [the “else statement;” part is optional] while (condition) statement; for (initialize; test; step) statement; Curly braces are used to group statements. if (x < y) {tmp = x; x = y; y = tmp;} But: can’t declare new variables at the beginning of a block; only at beginning of a function. This is not legal in C: if (x < y){int tmp = x; x = y; y = tmp;}

6 CS100A, Fall 1997, Lectures 226 C Functions A C program is a collection of functions. The syntax is much like Java, but, since there are no classes, function declarations appear freely in the source program. There is no explicit notion of public or private access in C. Example: /* Yield maximum of x and y */ int max (int x, int y) { if (x >= y) return x; else return y; }

7 CS100A, Fall 1997, Lectures 227 Void Functions A function that does not return an explicit value is given a result type of void. /* Print n lines of stars containing 1, 2, 3, …, n stars per line. */ void print_stars (int n) { int j, k; for (k = 1; k <= n; k++) { /* inv: lines containing 1, …, k-1 stars have been printed. */ /* print line with k stars */ for (j = 1; j <= k; j++) printf(“*”); printf(“\n”) }

8 CS100A, Fall 1997, Lectures 228.c Source 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 only be called by other functions defined in the same file. External (“global”) variables may be defined in.c files outside of any function. External variables are created when the program begins execution and retain their values until the program finishes. External variables may also be defined static to restrict access to the file containing the variable definition.

9 CS100A, Fall 1997, Lectures 229.h Header Files Every function (and external variable) must be defined exactly once by giving a full definition in some.c source file. A function (external variable) may be called (referenced) in other files provided that there is a declaration of the function (ext. 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 (names ending in “.h”). The declarations in a header file xyz.h can be incorporated in another file by the directive #include “xyz.h” (for user files) or, for standard C libraries, #include

10 CS100A, Fall 1997, Lectures 2210 Example: Standard Math Library The file math.h includes 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 with the appropriate #include directive. #include /* yield twice the square root of x */ double sqrt2 (double x) { return 2 * sqrt(x); }

11 CS100A, Fall 1997, Lectures 2211 Standard Output — printf The library includes basic routines to read formatted data from the standard input (usually keyboard) and print on the standard output (usually the screen). The basic output routine is printf. It has one or more arguments: the first is the “format string”. This string contains literal text to be printed interspersed with formatting instructions for the remaining arguments. Example: Print Fahrenheit-Celsius table. #include void main (void) { int f; printf(“Fahrenheit Celsius\n”); for (f = 0; f <= 300; f = f + 20) printf(“%3d %6.1f\n”, f, (5.0/9.0) * (f-32) ); }

12 CS100A, Fall 1997, Lectures 2212 Parameters and Arguments As in Java, when a C function is called, space is allocated for the function’s parameters, and these are initialized with the values of the corresponding arguments. Example: What output is produced by this program? #include 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); }

13 CS100A, Fall 1997, Lectures 2213 Pointers and References Suppose that we wanted function f to actually interchange the values of the argument variables j and k? To do that, f needs to be able to refer to the variables themselves, not just a copy of their values at the time the function begins execution. C provides operators to create pointers to variables and, given a pointer to a variable, to access the contents of that variable. If v is a variable, the expression &v is a pointer that refers to it. If v is a variable of type t, the pointer &v is said to have type “t *”, or “pointer to t”. If p is a pointer to a variable, the expression *p refers to the variable itself. If the pointer p has type “t *” (pointer to t), the expression *p has type t.

14 CS100A, Fall 1997, Lectures 2214 Example Revisited Revise the main program to create pointers to variables j and k and use these pointers as arguments to function f. #include void main(void) { int j = 17; int k = 42; f (&j, &k); printf(“j = %d, k = %d\n”, j, k); }

15 CS100A, Fall 1997, Lectures 2215 Example Revisited (cont.) The function f needs two changes. First, the parameter types are no longer int, but pointer to int, so the parameter list must be modified. Second, the pointers must be dereferenced to access the contents of the actual variables. void f (int * x, int * y) { int tmp; tmp = *x; *x = *y; *y = tmp; }

16 CS100A, Fall 1997, Lectures 2216 Example Revisited (cont.) Execution:

17 CS100A, Fall 1997, Lectures 2217 Standard Input — scanf The function scanf in reads from standard input and deciphers the input characters according to the format string given as its first argument. The remaining arguments to scanf are pointers to variables where the input values should be stored. As with printf, C processors generally can’t (or don’t) check that the types of the variables match the format codes in the string. A mismatch often will lead to mysteriously scrambled bytes in memory (if you’re lucky) or a program or machine crash (if you’re not).

18 CS100A, Fall 1997, Lectures 2218 Scanf Example Here is a simple example that uses scanf and the max function defined in a previous slide. void main(void) { int j,k; printf(“please enter two numbers: ”); scanf(“%d %d”, &j, &k); printf("the larger of the two ”); printf(“ numbers was %d.\n", max(j, k) ); }


Download ppt "CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:"

Similar presentations


Ads by Google