CS100A, Fall 1997

advertisement
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.
CS100A, Fall 1997, Lectures 22
1
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.
CS100A, Fall 1997, Lectures 22
2
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.
CS100A, Fall 1997, Lectures 22
3
•
•
•
•
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.
CS100A, Fall 1997, Lectures 22
4
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;}
CS100A, Fall 1997, Lectures 22
5
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;
}
CS100A, Fall 1997, Lectures 22
6
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”)
}
}
CS100A, Fall 1997, Lectures 22
7
•
•
•
•
.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.
CS100A, Fall 1997, Lectures 22
8
•
•
•
•
.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 <xyz.h>
CS100A, Fall 1997, Lectures 22
9
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 <math.h>
/* yield twice the square root of x */
double sqrt2 (double x) {
return 2 * sqrt(x);
}
CS100A, Fall 1997, Lectures 22
10
Standard Output — printf
• The library <stdio.h> 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 <stdio.h>
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) );
}
CS100A, Fall 1997, Lectures 22
11
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 <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);
}
CS100A, Fall 1997, Lectures 22
12
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.
CS100A, Fall 1997, Lectures 22
13
Example Revisited
• Revise the main program to create pointers
to variables j and k and use these pointers as
arguments to function f.
#include <stdio.h>
void main(void) {
int j = 17;
int k = 42;
f (&j, &k);
printf(“j = %d, k = %d\n”, j, k);
}
CS100A, Fall 1997, Lectures 22
14
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;
}
CS100A, Fall 1997, Lectures 22
15
Example Revisited (cont.)
• Execution:
CS100A, Fall 1997, Lectures 22
16
Standard Input — scanf
• The function scanf in <stdio.h> 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).
CS100A, Fall 1997, Lectures 22
17
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) );
}
CS100A, Fall 1997, Lectures 22
18
Download