Monday, January 26, 2009

Floating Point

We've skipped over floating point so far, and the treatment here will be hasty. C has single and double precision numbers (where the precision depends on the machine at hand). For example,

double sum;
float avg, y[10];
sum = 0.0;
for( i=0; i
sum =+ y[i];
avg = sum/n;

forms the sum and average of the array y.
All floating arithmetic is done in double precision. Mixed mode arithmetic is legal; if an arithmetic operator in an expression has both operands int or char, the arithmetic done is integer, but if one operand is int or char and the other is float or double, both operands are converted to double. Thus if i and j are int and x is float,

(x+i)/j converts i and j to float
x + i/j does i/j integer, then converts

Type conversion may be made by assignment; for instance,

int m, n;
float x, y;
m = x;
y = n;

converts x to integer (truncating toward zero), and n to floating point.
Floating constants are just like those in Fortran or PL/I, except that the exponent letter is `e' instead of `E'. Thus:

pi = 3.14159;
large = 1.23456789e10;

printf will format floating point numbers: ``%w.df'' in the format string will print the corresponding variable in a field w digits wide, with d decimal places. An e instead of an f will produce exponential notation.


Kia Dealers - Get multiple Kia price quotes from competing Kia Dealers


Used Autos - Autotropolis.com is your #1 stop for auto reviews and comparisons on new automobiles and trucks.
cigars - Cigar Experience is a great site to find information on all your favorite brands of top quality cigars.

Bit Operators in C Program

C has several operators for logical bit-operations. For example,
x = x & 0177;
forms the bit-wise AND of x and 0177, effectively retaining only the last seven bits of x. Other operators are
| inclusive OR
^ (circumflex) exclusive OR
~ (tilde) 1's complement
! logical NOT
<< left shift (as in x<<2)
>> right shift (arithmetic on PDP-11; logical on H6070, IBM360)

Assignment Operators

An unusual feature of C is that the normal binary operators like `+', `-', etc. can be combined with the assignment operator `=' to form new assignment operators. For example,
x =- 10;
uses the assignment operator `=-' to decrement x by 10, and
x =& 0177
forms the AND of x and 0177. This convention is a useful notational shortcut, particularly if x is a complicated expression. The classic example is summing an array:
for( sum=i=0; i sum =+ array[i];
But the spaces around the operator are critical! For
x = -10;
sets x to -10, while
x =- 10;
subtracts 10 from x. When no space is present,
x=-10;
also decreases x by 10. This is quite contrary to the experience of most programmers. In particular, watch out for things like
c=*s++;
y=&x[0];
both of which are almost certainly not what you wanted. Newer versions of various compilers are courteous enough to warn you about the ambiguity.
Because all other operators in an expression are evaluated before the assignment operator, the order of evaluation should be watched carefully:
x = x<means ``shift x left y places, then OR with z, and store in x.'' But
x =<< y | z;
means ``shift x left by y|z places'', which is rather different.

#define, #include - macro

C provides a very limited macro facility. You can say

#define name something
and thereafter anywhere ``name'' appears as a token, ``something'' will be substituted. This is particularly useful in parametering the sizes of arrays:
#define ARRAYSIZE 100
int arr[ARRAYSIZE];
...
while( i++ < ARRAYSIZE )...
(now we can alter the entire program by changing only the define) or in setting up mysterious constants:
#define SET 01
#define INTERRUPT 02 /* interrupt bit */
#define ENABLED 04
...
if( x & (SET | INTERRUPT | ENABLED) ) ...

Now we have meaningful words instead of mysterious constants. (The mysterious operators `&' (AND) and `|' (OR) will be covered in the next section.) It's an excellent practice to write programs without any literal constants except in #define statements.
There are several warnings about #define. First, there's no semicolon at the end of a #define; all the text from the name to the end of the line (except for comments) is taken to be the ``something''. When it's put into the text, blanks are placed around it. Good style typically makes the name in the #define upper case; this makes parameters more visible. Definitions affect things only after they occur, and only within the file in which they occur. Defines can't be nested. Last, if there is a #define in a file, then the first character of the file must be a `#', to signal the preprocessor that definitions exist.
The other control word known to C is #include. To include one file in your source at compilation time, say

#include "filename"

This is useful for putting a lot of heavily used data definitions and #define statements at the beginning of a file to be compiled. As with #define, the first line of a file containing a #include has to begin with a `#'. And #include can't be nested -- an included file can't contain another #include.

Initialization of Variables in C Program

An external variable may be initialized at compile time by following its name with an initializing value when it is defined. The initializing value has to be something whose value is known at compile time, like a constant.
int x 0; /* "0" could be any constant */
int a 'a';
char flag 0177;
int *p &y[1]; /* p now points to y[1] */
An external array can be initialized by following its name with a list of initializations enclosed in braces:
int x[4] {0,1,2,3}; /* makes x[i] = i */
int y[ ] {0,1,2,3}; /* makes y big enough for 4 values */
char *msg "syntax error\n"; /* braces unnecessary here */
char *keyword[ ]{
"if",
"else",
"for",
"while",
"break",
"continue",
0
};
This last one is very useful -- it makes keyword an array of pointers to character strings, with a zero at the end so we can identify the last element easily. A simple lookup routine could scan this until it either finds a match or encounters a zero keyword pointer:
lookup(str) /* search for str in keyword[ ] */
char *str; {
int i,j,r;
for( i=0; keyword[i] != 0; i++) {
for( j=0; (r=keyword[i][j]) == str[j] && r != '\0'; j++ );
if( r == str[j] )
return(i);
}
return(-1);
}

Structures in C Program

The main use of structures is to lump together collections of disparate variable types, so they can conveniently be treated as a unit. For example, if we were writing a compiler or assembler, we might need for each identifier information like its name (a character array), its source line number (an integer), some type information (a character, perhaps), and probably a usage count (another integer).
char id[10];
int line;
char type;
int usage;
We can make a structure out of this quite easily. We first tell C what the structure will look like, that is, what kinds of things it contains; after that we can actually reserve storage for it, either in the same statement or separately. The simplest thing is to define it and allocate storage all at once:
struct {
char id[10];
int line;
char type;
int usage;
} sym;
This defines sym to be a structure with the specified shape; id, line, type and usage are members of the structure. The way we refer to any particular member of the structure is
structure-name . member
as in
sym.type = 077;
if( sym.usage == 0 ) ...
while( sym.id[j++] ) ...
etc.
Although the names of structure members never stand alone, they still have to be unique; there can't be another id or usage in some other structure.
So far we haven't gained much. The advantages of structures start to come when we have arrays of structures, or when we want to pass complicated data layouts between functions. Suppose we wanted to make a symbol table for up to 100 identifiers. We could extend our definitions like
char id[100][10];
int line[100];
char type[100];
int usage[100];
but a structure lets us rearrange this spread-out information so all the data about a single identifer is collected into one lump:
struct {
char id[10];
int line;
char type;
int usage;
} sym[100];
This makes sym an array of structures; each array element has the specified shape. Now we can refer to members as
sym[i].usage++; /* increment usage of i-th identifier */
for( j=0; sym[i].id[j++] != '\0'; ) ...
etc.
Thus to print a list of all identifiers that haven't been used, together with their line number,
for( i=0; i if( sym[i].usage == 0 )
printf("%d\t%s\n", sym[i].line, sym[i].id);
Suppose we now want to write a function lookup(name) which will tell us if name already exists in sym, by giving its index, or that it doesn't, by returning a -1. We can't pass a structure to a function directly; we have to either define it externally, or pass a pointer to it. Let's try the first way first.
int nsym 0; /* current length of symbol table */

struct {
char id[10];
int line;
char type;
int usage;
} sym[100]; /* symbol table */

main( ) {
...
if( (index = lookup(newname)) >= 0 )
sym[index].usage++; /* already there ... */
else
install(newname, newline, newtype);
...
}

lookup(s)
char *s; {
int i;
extern struct {
char id[10];
int line;
char type;
int usage;
} sym[ ];

for( i=0; i if( compar(s, sym[i].id) > 0 )
return(i);
return(-1);
}

compar(s1,s2) /* return 1 if s1==s2, 0 otherwise */
char *s1, *s2; {
while( *s1++ == *s2 )
if( *s2++ == '\0' )
return(1);
return(0);
}
The declaration of the structure in lookup isn't needed if the external definition precedes its use in the same source file, as we shall see in a moment.
Now what if we want to use pointers?
struct symtag {
char id[10];
int line;
char type;
int usage;
} sym[100], *psym;

psym = &sym[0]; /* or p = sym; */
This makes psym a pointer to our kind of structure (the symbol table), then initializes it to point to the first element of sym.
Notice that we added something after the word struct: a ``tag'' called symtag. This puts a name on our structure definition so we can refer to it later without repeating the definition. It's not necessary but useful. In fact we could have said
struct symtag {
... structure definition
};
which wouldn't have assigned any storage at all, and then said
struct symtag sym[100];
struct symtag *psym;
which would define the array and the pointer. This could be condensed further, to
struct symtag sym[100], *psym;
The way we actually refer to an member of a structure by a pointer is like this:
ptr -> structure-member
The symbol `->' means we're pointing at a member of a structure; `->' is only used in that context. ptr is a pointer to the (base of) a structure that contains the structure member. The expression ptr->structure-member refers to the indicated member of the pointed-to structure. Thus we have constructions like:
psym->type = 1;
psym->id[0] = 'a';
and so on.
For more complicated pointer expressions, it's wise to use parentheses to make it clear who goes with what. For example,
struct { int x, *y; } *p;
p->x++ increments x
++p->x so does this!
(++p)->x increments p before getting x
*p->y++ uses y as a pointer, then increments it
*(p->y)++ so does this
*(p++)->y uses y as a pointer, then increments p
The way to remember these is that ->, . (dot), ( ) and [ ] bind very tightly. An expression involving one of these is treated as a unit. p->x, a[i], y.x and f(b) are names exactly as abc is.
If p is a pointer to a structure, any arithmetic on p takes into account the actual size of the structure. For instance, p++ increments p by the correct amount to get the next element of the array of structures. But don't assume that the size of a structure is the sum of the sizes of its members -- because of alignments of different sized objects, there may be ``holes'' in a structure.
Enough theory. Here is the lookup example, this time with pointers.
struct symtag {
char id[10];
int line;
char type;
int usage;
} sym[100];

main( ) {
struct symtag *lookup( );
struct symtag *psym;
...
if( (psym = lookup(newname)) ) /* non-zero pointer */
psym -> usage++; /* means already
there */
else
install(newname, newline, newtype);
...
}

struct symtag *lookup(s)
char *s; {
struct symtag *p;
for( p=sym; p < &sym[nsym]; p++ )
if( compar(s, p->id) > 0)
return(p);
return(0);
}
The function compar doesn't change: `p->id' refers to a string.
In main we test the pointer returned by lookup against zero, relying on the fact that a pointer is by definition never zero when it really points at something. The other pointer manipulations are trivial.
The only complexity is the set of lines like
struct symtag *lookup( );
This brings us to an area that we will treat only hurriedly; the question of function types. So far, all of our functions have returned integers (or characters, which are much the same). What do we do when the function returns something else, like a pointer to a structure? The rule is that any function that doesn't return an int has to say explicitly what it does return. The type information goes before the function name (which can make the name hard to see).
Examples:
char f(a)
int a; {
...
}

int *g( ) { ... }

struct symtag *lookup(s) char *s; { ... }
The function f returns a character, g returns a pointer to an integer, and lookup returns a pointer to a structure that looks like symtag. And if we're going to use one of these functions, we have to make a declaration where we use it, as we did in main above.
Notice the parallelism between the declarations
struct symtag *lookup( );
struct symtag *psym;
In effect, this says that lookup( ) and psym are both used the same way - as a pointer to a structure -- even though one is a variable and the other is a function.

The Switch Statement; Break; Continue

The switch statement can be used to replace the multi-way test we used in the last example. When the tests are like this:

if( c == 'a' ) ...
else if( c == 'b' ) ...
else if( c == 'c' ) ...
else ...

testing a value against a series of constants, the switch statement is often clearer and usually gives better code. Use it like this:

switch( c ) {

case 'a':
aflag++;
break;
case 'b':
bflag++;
break;
case 'c':
cflag++;
break;
default:
printf("%c?\n", c);
break;
}

The case statements label the various actions we want; default gets done if none of the other cases are satisfied. (A default is optional; if it isn't there, and none of the cases match, you just fall out the bottom.)
The break statement in this example is new. It is there because the cases are just labels, and after you do one of them, you fall through to the next unless you take some explicit action to escape. This is a mixed blessing. On the positive side, you can have multiple cases on a single statement; we might want to allow both upper and lower

case 'a': case 'A': ...

case 'b': case 'B': ...
etc.

But what if we just want to get out after doing case `a' ? We could get out of a case of the switch with a label and a goto, but this is really ugly. The break statement lets us exit without either goto or label.

switch( c ) {

case 'a':
aflag++;
break;
case 'b':
bflag++;
break;
...
}

/* the break statements get us here directly */
The break statement also works in for and while statements; it causes an immediate exit from the loop.
The continue statement works only inside for's and while's; it causes the next iteration of the loop to be started. This means it goes to the increment part of the for and the test part of the while. We could have used a continue in our example to get on with the next iteration of the for, but it seems clearer to use break instead.