Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: lets C
Description: Basics of C language and its brief concepts.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


1

2
Preface
...
8
Chapter 1 - A Tutorial Introduction
...
1 Getting Started
...
2 Variables and Arithmetic Expressions
...
3 The for statement
...
4 Symbolic Constants
...
5 Character Input and Output
...
5
...
18
1
...
2 Character Counting
...
5
...
20
1
...
4 Word Counting
...
6 Arrays
...
7 Functions
...
8 Arguments - Call by Value
...
9 Character Arrays
...
10 External Variables and Scope
...
35
2
...
35
2
...
35
2
...
36
2
...
38
2
...
39
2
...
39
2
...
40
2
...
43
2
...
45
2
...
46
2
...
47
2
...
48
Chapter 3 - Control Flow
...
1 Statements and Blocks
...
2 If-Else
...
3 Else-If
...
4 Switch
...
5 Loops - While and For
...
6 Loops - Do-While
...
7 Break and Continue
...
8 Goto and labels
...
59
4
...
59
4
...
62
4
...
63
4
...
68
4
...
69
4
...
70
4
...
71
4
...
72
4
...
72
4
...
73
4
...
74
4
...
1 File Inclusion
...
11
...
75
4
...
3 Conditional Inclusion
...
78
5
...
78
5
...
79
5
...
81
5
...
84
5
...
87
5
...
89
5
...
92
5
...
93
5
...
Multi-dimensional Arrays
...
10 Command-line Arguments
...
11 Pointers to Functions
...
12 Complicated Declarations
...
105
6
...
105
6
...
107
6
...
109
6
...
112
6
...
113
6
...
117
6
...
119
6
...
120
6
...
121
Chapter 7 - Input and Output
...
1 Standard Input and Output
...
2 Formatted Output - printf
...
3 Variable-length Argument Lists
...
4 Formatted Input - Scanf
...
5 File Access
...
6 Error Handling - Stderr and Exit
...
7 Line Input and Output
...
8 Miscellaneous Functions
...
8
...
135
7
...
2 Character Class Testing and Conversion
...
8
...
135
7
...
4 Command Execution
...
8
...
136
7
...
6 Mathematical Functions
...
8
...
136
Chapter 8 - The UNIX System Interface
...
1 File Descriptors
...
2 Low Level I/O - Read and Write
...
3 Open, Creat, Close, Unlink
...
4 Random Access - Lseek
...
5 Example - An implementation of Fopen and Getc
...
6 Example - Listing Directories
...
7 Example - A Storage Allocator
...
154
A
...
154
A
...
154
A
...
1 Tokens
...
2
...
154
A
...
3 Identifiers
...
2
...
154

4
A
...
5 Constants
...
2
...
156
A
...
156
A
...
157
A
...
1 Storage Class
...
4
...
157
A
...
3 Derived types
...
4
...
158
A
...
158
A
...
159
A
...
1 Integral Promotion
...
6
...
159
A
...
3 Integer and Floating
...
6
...
159
A
...
5 Arithmetic Conversions
...
6
...
160
A
...
7 Void
...
6
...
161
A
...
161
A
...
1 Pointer Conversion
...
7
...
161
A
...
3 Postfix Expressions
...
7
...
164
A
...
5 Casts
...
7
...
165
A
...
7 Additive Operators
...
7
...
166
A
...
9 Relational Operators
...
7
...
167
A
...
11 Bitwise AND Operator
...
7
...
167
A
...
13 Bitwise Inclusive OR Operator
...
7
...
168
A
...
15 Logical OR Operator
...
7
...
168
A
...
17 Assignment Expressions
...
7
...
169
A
...
19 Constant Expressions
...
8 Declarations
...
8
...
170
A
...
2 Type Specifiers
...
8
...
172
A
...
4 Enumerations
...
8
...
175
A
...
6 Meaning of Declarators
...
8
...
178
A
...
8 Type names
...
8
...
181
A
...
10 Type Equivalence
...
9 Statements
...
9
...
182
A
...
2 Expression Statement
...
9
...
182
A
...
4 Selection Statements
...
9
...
183
A
...
6 Jump statements
...
10 External Declarations
...
10
...
185
A
...
2 External Declarations
...
11 Scope and Linkage
...
11
...
187
A
...
2 Linkage
...
12 Preprocessing
...
12
...
188
A
...
2 Line Splicing
...
12
...
189
A
...
4 File Inclusion
...
12
...
191
A
...
6 Line Control
...
12
...
192
A
...
8 Pragmas
...
12
...
192
A
...
10 Predefined names
...
13 Grammar
...
200
B
...
h>
...
1
...
200
B
...
2 Formatted Output
...
1
...
203
B
...
4 Character Input and Output Functions
...
1
...
205
B
...
6 File Positioning Functions
...
1
...
206
B
...
h>
...
3 String Functions: ...
206
B
...
h>
...
5 Utility Functions: ...
208
B
...
h>
...
7 Variable Argument Lists: ...
210
B
...
h>
...
9 Signals: ...
211
B
...
h>
...
11 Implementation-defined Limits: ...
h>
...
215

6

Preface
The computing world has undergone a revolution since the publication of The C
Programming Language in 1978
...
During this time, C has changed too,
although only modestly, and it has spread far beyond its origins as the language of the UNIX
operating system
...
In 1983, the American National Standards Institute (ANSI) established a committee
whose goal was to produce ``an unambiguous and machine-independent definition of the
language C'', while still retaining its spirit
...

The standard formalizes constructions that were hinted but not described in the first edition,
particularly structure assignment and enumerations
...
It specifies a standard library,
with an extensive set of functions for performing input and output, memory management,
string manipulation, and similar tasks
...

This Second Edition of The C Programming Language describes C as defined by the ANSI
standard
...
For the most part, this makes no significant
difference; the most visible change is the new form of function declaration and definition
...

We have tried to retain the brevity of the first edition
...
We have improved the exposition of critical features, such as
pointers, that are central to C programming
...
For instance, the treatment of complicated
declarations is augmented by programs that convert declarations into words and vice versa
...

Appendix A, the reference manual, is not the standard, but our attempt to convey the
essentials of the standard in a smaller space
...
Appendix B is a summary of the facilities of the standard library
...
Appendix C is a concise summary of
the changes from the original version
...
With a decade more experience, we still feel that way
...

We are deeply indebted to friends who helped us to produce this second edition
...
We are grateful for careful reading by Al Aho,
Dennis Allison, Joe Campbell, G
...
Emlin, Karen Fortgang, Allen Holub, Andrew Hume,
Dave Kristol, John Linderman, Dave Prosser, Gene Spafford, and Chris van Wyk
...
Dave Prosser answered

7
many detailed questions about the ANSI standard
...
Rich Drechsler helped greatly with typesetting
...

Brian W
...
Ritchie

8

Preface to the first edition
C is a general-purpose programming language with features economy of expression, modern
flow control and data structures, and a rich set of operators
...
But its
` '
absence of restrictions and its generality make it more convenient and effective for many
tasks than supposedly more powerful languages
...
The operating system, the C compiler, and essentially all UNIX
applications programs (including all of the software used to prepare this book) are written in
C
...
C is not tied to any particular
hardware or system, however, and it is easy to write programs that will run without change on
any machine that supports C
...
It contains a tutorial
introduction to get new users started as soon as possible, separate chapters on each major
feature, and a reference manual
...
For the most part, the examples
are complete, real programs rather than isolated fragments
...
Besides showing how to make
effective use of the language, we have also tried where possible to illustrate useful algorithms
and principles of good style and sound design
...

Nonetheless, a novice programmer should be able to read along and pick up the language,
although access to more knowledgeable colleague will help
...
It is easy to learn, and it wears well as on' experience with it grows
...

The thoughtful criticisms and suggestions of many friends and colleagues have added greatly
to this book and to our pleasure in writing it
...
We are also indebted to Al Aho, Steve Bourne, Dan Dvorak, Chuck Haley, Debbie
Haley, Marion Harris, Rick Holt, Steve Johnson, John Mashey, Bob Mitze, Ralph Muha,
Peter Nelson, Elliot Pinson, Bill Plauger, Jerry Spivack, Ken Thompson, and Peter
Weinberger for helpful comments at various stages, and to Mile Lesk and Joe Ossanna for
invaluable assistance with typesetting
...
Kernighan
Dennis M
...
Our aim is to show the essential elements of the
language in real programs, but without getting bogged down in details, rules, and exceptions
...
We want to get you as quickly as possible to the point where you can
write useful programs, and to do that we have to concentrate on the basics: variables and
constants, arithmetic, control flow, functions, and the rudiments of input and output
...
These include pointers, structures, most of C' rich set of operators, several
s
control-flow statements, and the standard library
...
Most notable is that the complete story on any particular
feature is not found here, and the tutorial, by being brief, may also be misleading
...
We have tried to minimize these effects, but be warned
...
We hope that the repetition
will help you more than it annoys
...
Beginners should supplement it by writing small,
similar programs of their own
...


1
...
The first
program to write is the same for all languages:
Print the words
hello, world

This is a big hurdle; to leap over it you have to be able to create the program text somewhere,
compile it successfully, load it, run it, and find out where your output went
...

In C, the program to print `hello, world'is
`
'
#include ...
As a specific example, on
the UNIX operating system you must create the program in a file whose name ends in `
...
c, then compile it with the command
cc hello
...
out
...
out
by typing the command
a
...

Now, for some explanations about the program itself
...
A function contains statements that specify the computing
operations to be done, and variables store values used during the computation
...

Our example is a function named main
...
This means that every program must have a main somewhere
...
The first line of the program,
main

#include ...
The standard library is described in Chapter
7 and Appendix B
...
The parentheses after the function
name surround the argument list
...


#include ...
The function main contains only one
statement,
printf("hello, world\n");

A function is called by naming it, followed by a parenthesized list of arguments, so this calls
the function printf with the argument "hello, world\n"
...

A sequence of characters in double quotes, like "hello, world\n", is called a character
string or string constant
...

The sequence \n in the string is C notation for the newline character, which when printed
advances the output to the left margin on the next line
...
You must
use \n to include a newline character in the printf argument; if you try something like
printf("hello, world
");

the C compiler will produce an error message
...
Our first program could just as well have been written
printf

#include ...


Notice that \n represents only a single character
...

Among the others that C provides are \t for tab, \b for backspace, \" for the double quote
and \\ for the backslash itself
...
3
...
Run the `hello, world'program on your system
...

Exercise 1-2
...


1
...
It is longer
than the one that printed `hello, world' but not complicated
...

#include ...
, 300 */
main()
{
int fahr, celsius;
int lower, upper, step;
lower = 0;
upper = 300;
step = 20;

/* lower limit of temperature scale */
/* upper limit */
/* step size */

fahr = lower;
while (fahr <= upper) {
celsius = 5 * (fahr-32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr = fahr + step;
}
}

The two lines
/* print Fahrenheit-Celsius table
for fahr = 0, 20,
...
Any characters
between /* and */ are ignored by the compiler; they may be used freely to make a program
easier to understand
...

In C, all variables must be declared before they are used, usually at the beginning of the
function before any executable statements
...
e
...
The range of both int and
float depends on the machine you are using; 16-bits ints, which lie between -32768 and
+32767, are common, as are 32-bit ints
...

C provides several other data types besides int and float, including:

13
character - a single byte
short
short integer
long
long integer
double double-precision floating point
char

The size of these objects is also machine-dependent
...

Computation in the temperature conversion program begins with the assignment statements
lower = 0;
upper = 300;
step = 20;

which set the variables to their initial values
...

Each line of the table is computed the same way, so we use a loop that repeats once per
output line; this is the purpose of the while loop
while (fahr <= upper) {

...
If it is true (fahr
is less than or equal to upper), the body of the loop (the three statements enclosed in braces)

is executed
...
When the
test becomes false (fahr exceeds upper) the loop ends, and execution continues at the
statement that follows the loop
...

The body of a while can be one or more statements enclosed in braces, as in the temperature
converter, or a single statement without braces, as in
while (i < j)
i = 2 * i;

In either case, we will always indent the statements controlled by the while by one tab stop
(which we have shown as four spaces) so you can see at a glance which statements are inside
the loop
...
Although C
compilers do not care about how a program looks, proper indentation and spacing are critical
in making programs easy for people to read
...
The position of braces is less
important, although people hold passionate beliefs
...
Pick a style that suits you, then use it consistently
...
The Celsius temperature is computed and
assigned to the variable celsius by the statement
celsius = 5 * (fahr-32) / 9;

The reason for multiplying by 5 and dividing by 9 instead of just multiplying by 5/9 is that in
C, as in many other languages, integer division truncates: any fractional part is discarded
...
5/9 would be truncated to zero and so all the Celsius temperatures
would be reported as zero
...
printf is a general-purpose
output formatting function, which we will describe in detail in Chapter 7
...
) arguments is to be substituted, and in what form it is to be printed
...


printf("%d\t%d\n", fahr, celsius);
the values of the two integers fahr and celsius

to be printed, with a tab (\t) between

Each % construction in the first argument of printf is paired with the corresponding second
argument, third argument, etc
...

By the way, printf is not part of the C language; there is no input or output defined in C
itself
...
The behaviour of printf is defined in the ANSI standard,
however, so its properties should be the same with any compiler and library that conforms to
the standard
...

t
In particular, we will defer formatted input until then
...
4
...

There are a couple of problems with the temperature conversion program
...
That' easy to fix;
t
s
if we augment each %d in the printf statement with a width, the numbers printed will be
right-justified in their fields
...


-17
-6
4
15
26
37

The more serious problem is that because we have used integer arithmetic, the Celsius
temperatures are not very accurate; for instance, 0oF is actually about -17
...
To get
more accurate answers, we should use floating-point arithmetic instead of integer
...
Here is the second version:
#include ...
, 300; floating-point version */
main()
{
float fahr, celsius;
float lower, upper, step;
lower = 0;
upper = 300;
step = 20;

/* lower limit of temperatuire scale */
/* upper limit */
/* step size */

fahr = lower;
while (fahr <= upper) {
celsius = (5
...
0) * (fahr-32
...
0f %6
...
We were unable to use 5/9 in the
previous version because integer division would truncate it to zero
...
0/9
...

If an arithmetic operator has integer operands, an integer operation is performed
...
If we had written
(fahr-32), the 32 would be automatically converted to floating point
...

The detailed rules for when integers are converted to floating point are in Chapter 2
...

The printf conversion specification %3
...

%6
...
The output looks like this:
0
20
40

...
8
-6
...
4

Width and precision may be omitted from a specification: %6f says that the number is to be at
least six characters wide; %
...

%d
print as decimal integer
%6d
print as decimal integer, at least 6 characters wide
%f
print as floating point
%6f
print as floating point, at least 6 characters wide
%
...
2f print as floating point, at least 6 wide and 2 after decimal point
Among others, printf also recognizes %o for octal, %x for hexadecimal, %c for character, %s
for character string and %% for itself
...
Modify the temperature conversion program to print a heading above the table
...
Write a program to print the corresponding Celsius to Fahrenheit table
...
3 The for statement
There are plenty of different ways to write a program for a particular task
...

#include ...
1f\n", fahr, (5
...
0)*(fahr-32));
}

This produces the same answers, but it certainly looks different
...
The
lower and upper limits and the step size appear only as constants in the for statement, itself a
new construction, and the expression that computes the Celsius temperature now appears as
the third argument of printf instead of a separate assignment statement
...
Since the
third argument of printf must be a floating-point value to match the %6
...

The for statement is a loop, a generalization of the while
...
Within the parentheses, there are three parts, separated
by semicolons
...
The second part is the
test or condition that controls the loop:
fahr <= 300

This condition is evaluated; if it is true, the body of the loop (here a single ptintf) is
executed
...
The loop terminates if the condition has become
false
...
The initialization, condition and increment can be any
expressions
...
The for is
usually appropriate for loops in which the initialization and increment are single statements
and logically related, since it is more compact than while and it keeps the loop control
statements together in one place
...
Modify the temperature conversion program to print the table in reverse order,
that is, from 300 degrees to 0
...
4 Symbolic Constants
A final observation before we leave temperature conversion forever
...

One way to deal with magic numbers is to give them meaningful names
...
The name has the same form as a variable
name: a sequence of letters and digits that begins with a letter
...

#include ...
1f\n", fahr, (5
...
0)*(fahr-32));
}

The quantities LOWER, UPPER and STEP are symbolic constants, not variables, so they do not
appear in declarations
...
Notice that there is no
semicolon at the end of a #define line
...
5 Character Input and Output
We are going to consider a family of related programs for processing character data
...


18
The model of input and output supported by the standard library is very simple
...
A text stream is a sequence of characters divided into lines; each line consists of
zero or more characters followed by a newline character
...

The standard library provides several functions for reading or writing one character at a time,
of which getchar and putchar are the simplest
...
That is, after
c = getchar();

the variable c contains the next character of input
...

The function putchar prints a character each time it is called:
putchar(c);

prints the contents of the integer variable c as a character, usually on the screen
...


1
...
1 File Copying
Given getchar and putchar, you can write a surprising amount of useful code without
knowing anything more about input and output
...
h>

/* copy input to output; 1st version
main()
{
int c;

*/

c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}

The relational operator != means `not equal to'
`
'

...
The type char is specifically meant for storing such
character data, but any integer type can be used
...

The problem is distinguishing the end of input from valid data
...

any real character
...
We can' use char since c must be big
t
enough to hold EOF in addition to any possible char
...


19
is an integer defined in ...
By using the symbolic constant, we are assured that
nothing in the program depends on the specific numeric value
...
In
C, any assignment, such as
c = getchar();

is an expression and has a value, which is the value of the left hand side after the assignment
...
If the assignment of a
character to c is put inside the test part of a while loop, the copy program can be written this
way:
#include ...
If it was not, the body of the while is executed, printing the character
...
When the end of the input is finally reached, the while terminates and so
does main
...
The resulting program is more compact, and, once the idiom is mastered, easier
to read
...
(It' possible to get carried away and create impenetrable
ll
s
code, however, a tendency that we will try to curb
...
The precedence
of != is higher than that of =, which means that in the absence of parentheses the relational
test != would be done before the assignment =
...
(More on this in Chapter 2
...
Verify that the expression getchar() != EOF is 0 or 1
...
Write a program to print the value of EOF
...
5
...

#include ...
You could instead write nc =
nc + 1 but ++nc is more concise and often more efficient
...
The operators ++ and -- can be either prefix operators (++nc) or postfix
operators (nc++); these two forms have different values in expressions, as will be shown in
Chapter 2, but ++nc and nc++ both increment nc
...

The character counting program accumulates its count in a long variable instead of an int
...
Although on some machines, int and long are the same
size, on others an int is 16 bits, with a maximum value of 32767, and it would take relatively
little input to overflow an int counter
...

It may be possible to cope with even bigger numbers by using a double (double precision
We will also use a for statement instead of a while, to illustrate another way to write
the loop
...


#include ...
0f\n", nc);
}
printf

uses %f for both float and double; %
...


The body of this for loop is empty, because all the work is done in the test and increment
parts
...
The isolated
semicolon, called a null statement, is there to satisfy that requirement
...

Before we leave the character counting program, observe that if the input contains no
characters, the while or for test fails on the very first call to getchar, and the program
produces zero, the right answer
...
One of the nice things about while and
for is that they test at the top of the loop, before proceeding with the body
...
Programs
should act intelligently when given zero-length input
...


1
...
3 Line Counting
The next program counts input lines
...
Hence,
counting lines is just counting newlines:
#include ...
The
if statement tests the parenthesized condition, and if the condition is true, executes the
statement (or group of statements in braces) that follows
...

The double equals sign == is the C notation for `is equal to'
`
'(like Pascal' single = or
s
Fortran'
...
This symbol is used to distinguish the equality test from the single = that C
s
uses for assignment
...
As we will see in Chapter 2, the result is usually a legal expression, so you will get
no warning
...
This is called a character constant,
s
although it is just another way to write a small integer
...
Of course, 'A' is to be preferred over 65: its meaning is obvious, and it is independent of a
particular character set
...
You should note carefully
that '\n' is a single character, and in expressions is just an integer; on the other hand, '\n' is
a string constant that happens to contain only one character
...

Exercise 1-8
...

Exercise 1-9
...

Exercise 1-10
...
This makes tabs and backspaces visible in an
unambiguous way
...
5
...
This is a bare-bones version of the UNIX program wc
...
h>
#define IN
#define OUT

1
0

/* inside a word */
/* outside a word */

/* count lines, words, and characters in input */
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;

22
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c = '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}

Every time the program encounters the first character of a word, it counts one more word
...
We prefer the symbolic constants IN and
`
'
,
OUT to the literal values 1 and 0 because they make the program more readable
...
You' also find that it'
ll
s
easier to make extensive changes in programs where magic numbers appear only as symbolic
constants
...
This is not a special case, but a consequence of the fact that an
assignment is an expression with the value and assignments associated from right to left
...


that the escape sequence \t is a
visible representation of the tab character
...
Expressions connected by && or || are evaluated left to
right, and it is guaranteed that evaluation will stop as soon as the truth or falsehood is known
...
This isn'particularly important here, but is significant in more complicated situations,
t
as we will soon see
...
The general form is
if (expression)
statement1
else
statement2

One and only one of the two statements associated with an if-else is performed
...
Each statement can
be a single statement or several in braces
...

Exercise 1-11
...
Write a program that prints its input one word per line
...
6 Arrays
Let is write a program to count the number of occurrences of each digit, of white space
characters (blank, tab, newline), and of all other characters
...

There are twelve categories of input, so it is convenient to use an array to hold the number of
occurrences of each digit, rather than ten individual variables
...
h>
/* count digits, white space, others */
main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n",
nwhite, nother);
}

The output of this program on itself is
digits = 9 3 0 0 0 0 0 0 0 1, white space = 123, other = 345

The declaration

int ndigit[10];

declares ndigit to be an array of 10 integers
...
, ndigit[9]
...

A subscript can be any integer expression, which includes integer variables like i, and integer
constants
...

For example, the test
if (c >= '0' && c <= '9')

determines whether the character in c is a digit
...
, '9' have consecutive increasing values
...

By definition, chars are just small integers, so char variables and constants are identical to
in arithmetic expressions
...

ints

The decision as to whether a character is a digit, white space, or something else is made with
the sequence
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else

25
++nother;

The pattern

if (condition1)
statement1
else if (condition2)
statement2

...

else
statementn

occurs frequently in programs as a way to express a multi-way decision
...
(Any
statement can be several statements enclosed in braces
...
If the final else and statement
are omitted, as in the word count program, no action takes place
...

As a matter of style, it is advisable to format this construction as we have shown; if each if
were indented past the previous else, a long sequence of decisions would march off the right
side of the page
...
For contrast, we will present a switch
version of this program in Section 3
...

Exercise 1-13
...
It is
easy to draw the histogram with the bars horizontal; a vertical orientation is more
challenging
...
Write a program to print a histogram of the frequencies of different characters
in its input
...
7 Functions
In C, a function is equivalent to a subroutine or function in Fortran, or a procedure or function
in Pascal
...
With properly designed functions, it
is possible to ignore how a job is done; knowing what is done is sufficient
...

So far we have used only functions like printf, getchar and putchar that have been
provided for us; now it' time to write a few of our own
...
That is, the value of
power(2,5) is 32
...
(The standard
s
library contains a function pow(x,y) that computes xy
...


26
#include ...
If the source program appears in several files, you may
have to say more to compile and load it than if it all appears in one, but that is an operating
system matter, not a language attribute
...

The function power is called twice by main, in the line
printf("%d %d %d\n", i, power(2,i), power(-3,i));

Each call passes two arguments to power, which each time returns an integer to be formatted
and printed
...
(Not all functions
produce an integer value; we will take this up in Chapter 4
...

The names used by power for its parameters are local to power, and are not visible to any
other function: other routines can use the same names without conflict
...

We will generally use parameter for a variable named in the parenthesized list in a function
...

The value that power computes is returned to main by the return: statement
...
And the calling function can ignore a value returned by
a function
...
Since main is a
function like any other, it may return a value to its caller, which is in effect the environment
in which the program was executed
...
In the
interests of simplicity, we have omitted return statements from our main functions up to this
point, but we will include them hereafter, as a reminder that programs should return status to
their environment
...
This declaration, which is called a function prototype, has to agree with the definition
and uses of power
...

parameter names need not agree
...

A note of history: the biggest change between ANSI C and earlier versions is how functions
are declared and defined
...
(The body of the function is
the same as before
...
Indeed, since by default power would have been assumed to return an
int, the entire declaration might well have been omitted
...
The old style of declaration and definition still works
in ANSI C, at least for a transition period, but we strongly recommend that you use the new
form when you have a compiler that supports it
...
15
...
2 to use a function
for conversion
...
8 Arguments - Call by Value
One aspect of C functions may be unfamiliar to programmers who are used to some other
languages, particulary Fortran
...
'
`
'This
means that the called function is given the values of its arguments in temporary variables
rather than the originals
...

Call by value is an asset, however, not a liability
...
For example, here is a version of power that makes use of
this property
...
Whatever is
done to n inside power has no effect on the argument that power was originally called with
...
The caller must provide the address of the variable to be set (technically a pointer to

29
the variable), and the called function must declare the parameter to be a pointer and access
the variable indirectly through it
...

The story is different for arrays
...
By subscripting this value, the function can access and alter any
argument of the array
...


1
...
To illustrate the use of
character arrays and functions to manipulate them, let' write a program that reads a set of
s
text lines and prints the longest
...
One piece gets a
new line, another saves it, and the rest controls the process
...
Accordingly, let us
first write a separate function getline to fetch the next line of input
...
At the minimum, getline has to return a signal about
possible end of file; a more useful design would be to return the length of the line, or zero if
end of file is encountered
...
Every text line has at least one character; even a line containing only a newline
has length 1
...

This suggests a second function, copy, to copy the new line to a safe place
...
Here is the result
...
h>
#define MAXLINE 1000

/* maximum input line length */

int getline(char line[], int maxline);
void copy(char to[], char from[]);
/* print the longest input
main()
{
int len;
/*
int max;
/*
char line[MAXLINE];
char longest[MAXLINE];

line */
current line length */
maximum length seen so far */
/* current input line */
/* longest line saved here */

max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
}
/* getline: read a line into s, return length
int getline(char s[],int lim)
{
int c, i;

*/

for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}

The functions getline and copy are declared at the beginning of the program, which we
assume is contained in one file
...
In

int getline(char s[], int lim);

which specifies that the first argument, s, is an array, and the second, lim, is an integer
...
The length of
an array s is not necessary in getline since its size is set in main
...
This line also declares that
getline returns an int; since int is the default return type, it could be omitted
...
The return type of copy is void, which states explicitly that no value is
returned
...
This conversion is also used by
the C language: when a string constant like
getline

"hello\n"

appears in a C program, it is stored as an array of characters containing the characters in the
string and terminated with a '\0' to mark the end
...
copy also relies on the fact that its input argument is terminated with
a '\0', and copies this character into the output
...
For example, what should main do if it encounters a line which is
bigger than its limit? getline works safely, in that it stops collecting when the array is full,
even if no newline has been seen
...
In the interests of
brevity, we have ignored this issue
...
On the other hand, the user of copy already knows (or can
find out) how big the strings are, so we have chosen not to add error checking to it
...
Revise the main routine of the longest-line program so it will correctly print
the length of arbitrary long input lines, and as much as possible of the text
...
Write a program to print all input lines that are longer than 80 characters
...
Write a program to remove trailing blanks and tabs from each line of input,
and to delete entirely blank lines
...
Write a function reverse(s) that reverses the character string s
...


1
...
, are private or local to main
...
The same is true
of the variables in other functions; for example, the variable i in getline is unrelated to the i
in copy
...
This is why such variables are usually
known as automatic variables, following terminology in other languages
...
(Chapter 4 discusses the static
storage class, in which local variables do retain their values between calls
...
If they are not
set, they will contain garbage
...
(This
mechanism is rather like Fortran COMMON or Pascal variables declared in the outermost
block
...
Furthermore, because external
variables remain in existence permanently, rather than appearing and disappearing as
functions are called and exited, they retain their values even after the functions that set them
have returned
...
The variable must also be declared in each function that wants to access it; this
states the type of the variable
...
To make the discussion concrete, let us rewrite the longest-line
program with line, longest, and max as external variables
...

#include ...

Syntactically, external definitions are just like definitions of local variables, but since they
occur outside of functions, the variables are external
...

In certain circumstances, the extern declaration can be omitted
...
The extern declarations in main, getline
and copy are thus redundant
...

If the program is in several source files, and a variable is defined in file1 and used in file2 and
file3, then extern declarations are needed in file2 and file3 to connect the occurrences of the
variable
...
The suffix
...
The functions of the standard
library, for example, are declared in headers like ...
This topic is discussed at length
in Chapter 4, and the library itself in Chapter 7 and Appendix B
...
But for
compatibility with older C programs the standard takes an empty list as an old-style
declaration, and turns off all argument list checking; the word void must be used for an
explicitly empty list
...

You should note that we are using the words definition and declaration carefully when we
refer to external variables in this section
...


34
By the way, there is a tendency to make everything in sight an extern variable because it
appears to simplify communications - argument lists are short and variables are always there
when you want them
...

t
Relying too heavily on external variables is fraught with peril since it leads to programs
whose data connections are not all obvious - variables can be changed in unexpected and
even inadvertent ways, and the program is hard to modify
...

At this point we have covered what might be called the conventional core of C
...
These exercises suggest
programs of somewhat greater complexity than the ones earlier in this chapter
...
Write a program detab that replaces tabs in the input with the proper number
of blanks to space to the next tab stop
...

Should n be a variable or a symbolic parameter?
Exercise 1-21
...
Use the same tab stops as for detab
...
Write a program to `fold'long input lines into two or more shorter lines after
` '
the last non-blank character that occurs before the n-th column of input
...

Exercise 1-23
...
Don'forget to
t
handle quoted strings and character constants properly
...

t
Exercise 1-24
...
Don' forget about quotes, both single and
t
double, escape sequences, and comments
...
)

35

Chapter 2 - Types, Operators and
Expressions
Variables and constants are the basic data objects manipulated in a program
...
Operators specify what is to be done to them
...
The type of an object determines the set of values it can
have and what operations can be performed on it
...

The ANSI standard has made many small changes and additions to basic types and
expressions
...
Floating-point operations may
be done in single precision; there is also a long double type for extended precision
...
Enumerations have become part of the
language, formalizing a feature of long standing
...
The rules for automatic coercions among arithmetic types
have been augmented to handle the richer set of types
...
1 Variable Names
Although we didn'say so in Chapter 1, there are some restrictions on the names of variables
t
and symbolic constants
...
The underscore `_'
` 'counts as a letter; it is sometimes useful for improving the
readability of long variable names
...
Upper and lower case letters are distinct, so x and
X are two different names
...

At least the first 31 characters of an internal name are significant
...
For external names, the
standard guarantees uniqueness only for 6 characters and a single case
...
, are reserved: you can'use them as variable names
...

It' wise to choose variable names that are related to the purpose of the variable, and that are
s
unlikely to get mixed up typographically
...


2
...
short
and long apply to integers:
short int sh;
long int counter;
The word int can be omitted

in such declarations, and typically it is
...
short is often 16 bits long, and
int either 16 or 32 bits
...

The qualifier signed or unsigned may be applied to char or any integer
...
So, for instance, if chars are 8 bits, unsigned char variables have values
between 0 and 255, while signed chars have values between -128 and 127 (in a two'
s
complement machine
...

The type long double specifies extended-precision floating point
...

The standard headers ...
h> contain symbolic constants for all of these
sizes, along with other properties of the machine and compiler
...

Exercise 2-1
...
Harder if you compute them: determine the ranges of the various
floating-point types
...
3 Constants
An integer constant like 1234 is an int
...

Unsigned constants are written with a terminal u or U, and the suffix ul or UL indicates
unsigned long
...
4) or an exponent (1e-2) or both; their
type is double, unless suffixed
...

The value of an integer can be specified in octal or hexadecimal instead of decimal
...
For
example, decimal 31 can be written as 037 in octal and 0x1f or 0x1F in hex
...

0

A character constant is an integer,
'x'
...
For example, in the ASCII character set the character constant '0' has the value
48, which is unrelated to the numeric value 0
...
Character constants participate in numeric operations just as any other integers,
although they are most often used in comparisons with other characters
...
In
addition, an arbitrary byte-sized bit pattern can be specified by
'\ooo'

where ooo is one to three octal digits (0
...
9, a
...
F)
...
'\0'
is often written instead of 0 to emphasize the character nature of some expression, but the
numeric value is just 0
...
Such expressions may be
evaluated at during compilation rather than run-time, and accordingly may be used in any
place that a constant can occur, as in

or

#define MAXLINE 1000
char line[MAXLINE+1];
#define LEAP 1 /* in leap years */
int days[31+28+LEAP+31+30+31+30+31+31+30+31+30+31];

A string constant, or string literal, is a sequence of zero or more characters surrounded by
double quotes, as in
or

"I am a string"
"" /* the empty string */

The quotes are not part of the string, but serve only to delimit it
...
String
constants can be concatenated at compile time:
"hello, " "world"

is equivalent to

"hello, world"

This is useful for splitting up long strings across several source lines
...
The internal representation of a string
has a null character '\0' at the end, so the physical storage required is one more than the
number of characters written between the quotes
...
The standard library function strlen(s) returns the length of its character string
argument s, excluding the terminal '\0'
...
h>
...
The former is an integer, used to produce the numeric
value of the letter x in the machine' character set
...

There is one other kind of constant, the enumeration constant
...
If not all values are specified, unspecified values continue the progression from the
last specified value, as the second of these examples:
enum escapes { BELL = '\a', BACKSPACE = '\b', TAB = '\t',
NEWLINE = '\n', VTAB = '\v', RETURN = '\r' };
enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC };
/* FEB = 2, MAR = 3, etc
...
Values need not be distinct in the same
enumeration
...
Although
variables of enum types may be declared, compilers need not check that what you store in
such a variable is a valid value for the enumeration
...
In addition, a debugger may be
able to print values of enumeration variables in their symbolic form
...
4 Declarations
All variables must be declared before use, although certain declarations can be made
implicitly by content
...

A variable may also be initialized in its declaration
...
0e-5;

If the variable in question is not automatic, the initialization is done once only, conceptionally
before the program starts executing, and the initializer must be a constant expression
...
External and static variables are initialized to
zero by default
...
e
...

The qualifier const can be applied to the declaration of any variable to specify that its value
will not be changed
...

const double e = 2
...


2
...
Integer division
truncates any fractional part
...
For
example, a year is a leap year if it is divisible by 4 but not by 100, except that years divisible
by 400 are leap years
...
The direction of truncation for / and
the sign of the result for % are machine-dependent for negative operands, as is the action taken

on overflow or underflow
...
Arithmetic operators associate left to
right
...
1 at the end of this chapter summarizes precedence and associativity for all operators
...
6 Relational and Logical Operators
The relational operators are
>

>=

<

<=

They all have the same precedence
...

More interesting are the logical operators && and ||
...
Most C programs rely on these properties
...
Moreover, if this test fails, we must not go
on and read another character
...

The precedence of && is higher than that of ||, and both are lower than relational and equality
operators, so expressions like
i < lim-1 && (c=getchar()) != '\n' && c != EOF

need no extra parentheses
...

By definition, the numeric value of a relational or logical expression is 1 if the relation is true,
and 0 if the relation is false
...
A
common use of ! is in constructions like
if (!valid)

rather than

if (valid == 0)

It' hard to generalize about which form is better
...

'
),
Exercise 2-2
...


2
...
In general, the only automatic conversions are those
that convert a `narrower'operand into a `wider'one without losing information, such as
`
'
`
'
t
converting an integer into floating point in an expression like f + i
...
Expressions that might lose
information, like assigning a longer integer type to a shorter, or a floating-point type to an
integer, may draw a warning, but they are not illegal
...
This
permits considerable flexibility in certain kinds of character transformations
...

/* atoi: convert s to integer */
int atoi(char s[])
{
int i, n;
n = 0;
for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
n = 10 * n + (s[i] - '0');

41
return n;
}

As we discussed in Chapter 1, the expression
s[i] - '0'

gives the numeric value of the character stored in s[i], because the values of '0', '1', etc
...

Another example of char to int conversion is the function lower, which maps a single
character to lower case for the ASCII character set
...

/* lower: convert c to lower case; ASCII only */
int lower(int c)
{
if (c >= 'A' && c <= 'Z')
return c + 'a' - 'A';
else
return c;
}

This works for ASCII because corresponding upper case and lower case letters are a fixed
distance apart as numeric values and each alphabet is contiguous -- there is nothing but letters
between A and Z
...

The standard header ...
For example, the function
tolower is a portable replacement for the function lower shown above
...
h> functions from now on
...
The language does
not specify whether variables of type char are signed or unsigned quantities
...
On some machines a char whose leftmost
bit is 1 will be converted to a negative integer (`sign extension' On others, a char is
`
'
)
...

The definition of C guarantees that any character in the machine' standard printing character
s
set will never be negative, so these characters will always be positive quantities in
expressions
...
For portability, specify signed or unsigned if noncharacter data is to be stored in char variables
...
Thus the assignment
d = c >= '0' && c <= '9'
sets d to 1 if c is a digit, and 0 if

not
...
In the test part of if, while, for, etc
...

Implicit arithmetic conversions work much as expected
...
The result is of the integer
`
'

42
type
...
If there are no unsigned
operands, however, the following informal set of rules will suffice:


If either operand is long double, convert the other to long double
...




Otherwise, if either operand is float, convert the other to float
...




Then, if either operand is long, convert the other to long
...
In general, mathematical functions like those in
...
The main reason for using float is to save storage in
large arrays, or, less often, to save time on machines where double-precision arithmetic is
particularly expensive
...
The problem
is that comparisons between signed and unsigned values are machine-dependent, because
they depend on the sizes of the various integer types
...
Then -1L < 1U, because 1U, which is an unsigned int, is promoted to a
signed long
...

Conversions take place across assignments; the value of the right side is converted to the type
of the left, which is the type of the result
...

Longer integers are converted to shorter ones or to chars by dropping the excess high-order
bits
...
This is true whether or not sign extension is involved
...

If x is float and i is int, then x = i and i = x both cause conversions; float to int
causes truncation of any fractional part
...

Since an argument of a function call is an expression, type conversion also takes place when
arguments are passed to functions
...
This is why we have declared function arguments to
be int and double even when the function is called with char and float
...
In the construction
(type name) expression
the expression is converted to the named type by the conversion rules above
...
For example, the library routine sqrt

43
expects a double argument, and will produce nonsense if inadvertently handled something
else
...
h>
...
Note that the cast produces the
value of n in the proper type; n itself is not altered
...


If arguments are declared by a function prototype, as the normally should be, the declaration
causes automatic coercion of any arguments when the function is called
...
0 without any need for a cast
...
32767 */
int rand(void)
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}
/* srand: set seed for rand() */
void srand(unsigned int seed)
{
next = seed;
}
Exercise 2-3
...
The allowable digits are 0
through 9, a through f, and A through F
...
8 Increment and Decrement Operators
C provides two unusual operators for incrementing and decrementing variables
...
We
have frequently used ++ to increment variables, as in
if (c == '\n')
++nl;

The unusual aspect is that ++ and -- may be used either as prefix operators (before the
variable, as in ++n), or postfix operators (after the variable: n++)
...
But the expression ++n increments n before its value is used, while n++
increments n after its value has been used
...
If n is 5, then
x = n++;

sets x to 5, but
x = ++n;
sets x to 6
...
The increment and decrement operators can only be
applied to variables; an expression like (i+j)++ is illegal
...
But there are situations where one or the other is specifically
called for
...

/* squeeze: delete all c from s */
void squeeze(char s[], int c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
if (s[i] != c)
s[j++] = s[i];
s[j] = '\0';
}

Each time a non-c occurs, it is copied into the current j position, and only then is j
incremented to be ready for the next character
...
strcat assumes that there is enough space in s to hold the
combination
...

/* strcat: concatenate t to end of s; s must be big enough */
void strcat(char s[], char t[])
{
int i, j;
i = j = 0;
while (s[i] != '\0') /* find end of s */
i++;
while ((s[i++] = t[j++]) != '\0') /* copy t */
;
}

As each member is copied from t to s, the postfix ++ is applied to both i and j to make sure
that they are in position for the next pass through the loop
...
Write an alternative version of squeeze(s1,s2) that deletes each character in
s1 that matches any character in the string s2
...
Write the function any(s1,s2), which returns the first location in a string s1
where any character from the string s2 occurs, or -1 if s1 contains no characters from s2
...
)

45

2
...

&
bitwise AND
|
bitwise inclusive OR
^
bitwise exclusive OR
<< left shift
>> right shift
~
one' complement (unary)
s
The bitwise AND operator & is often used to mask off some set of bits, for example
n = n & 0177;

sets to zero all but the low-order 7 bits of n
...

The bitwise exclusive OR operator ^ sets a one in each bit position where its operands have
different bits, and zero where they are the same
...
For example, if x is 1 and y is 2, then x
& y is zero while x && y is one
...
Thus x << 2 shifts
the value of x by two positions, filling vacated bits with zero; this is equivalent to
multiplication by 4
...
Right shifting a signed quantity will fill with bit signs (`arithmetic shift' on some
`
'
)
machines and with 0-bits (`logical shift' on others
...
For example
x = x & ~077

sets the last six bits of x to zero
...
The
portable form involves no extra cost, since ~077 is a constant expression that can be
evaluated at compile time
...
We assume that bit
position 0 is at the right end and that n and p are sensible positive values
...

/* getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p+1-n)) & ~(~0 << n);
}
The expression x >> (p+1-n) moves the desired field to the right end of the word
...


is all
bits;

46
Exercise 2-6
...

Exercise 2-7
...
e
...

Exercise 2-8
...


2
...

Most binary operators (operators like + that have a left and right operand) have a
corresponding assignment operator op=, where op is one of
+

-

*

/

%

<<

>>

If expr1 and expr2 are expressions, then

&

^

|

expr1 op= expr2

is equivalent to

expr1 = (expr1) op (expr2)

except that expr1 is computed only once
...

/* bitcount: count 1 bits in x */
int bitcount(unsigned x)
{
int b;
for (b = 0; x != 0; x >>= 1)
if (x & 01)
b++;
return b;
}

Declaring the argument x to be an unsigned ensures that when it is right-shifted, vacated bits
will be filled with zeros, not sign bits, regardless of the machine the program is run on
...
We say `add 2 to i'or `increment i by 2' not `take i, add
`
2, then put the result back in i' Thus the expression i += 2 is preferable to i = i+2
...

addition, for a complicated expression like
yyval[yypv[p3+p4] + yypv[p1]] += 2

47
the assignment operator makes the code easier to understand, since the reader doesn'have to
t
check painstakingly that two long expressions are indeed the same, or to wonder why they'
re
not
...

We have already seen that the assignment statement has a value and can occur in expressions;
the most common example is
while ((c = getchar()) != EOF)

...


etc
...

Exercise 2-9
...
Explain why
...


2
...
The conditional expression, written with the ternary
operator `?:' provides an alternate way to write this and similar constructions
...
If it is non-zero (true), then the expression expr2 is
evaluated, and that is the value of the conditional expression
...
Only one of expr2 and expr3 is evaluated
...
If expr2 and expr3 are of different types, the type of the
result is determined by the conversion rules discussed earlier in this chapter
...


Parentheses are not necessary around the first expression of a conditional expression, since
the precedence of ?: is very low, just above assignment
...

The conditional expression often leads to succinct code
...

for (i = 0; i < n; i++)
printf("%6d%c", a[i], (i%10==9 || i==n-1) ? '\n' : ' ');
newline is printed after every tenth element, and after the n-th
...
This might look tricky, but it' more compact than the equivalent ifs
else
...
\n", n, n==1 ? "" : "s");

48
Exercise 2-10
...


2
...
1 summarizes the rules for precedence and associativity of all operators, including
those that we have not yet discussed
...
The `operator'() refers to function
call
...
are used to access members of structures; they will be covered in
Chapter 6, along with sizeof (size of an object)
...

Operators
Associativity
() [] ->
...

Table 2
...
This
implies that bit-testing expressions like
if ((x & MASK) == 0)
...

C, like most languages, does not specify the order in which the operands of an operator are
evaluated
...
)
x = f() + g();

may be evaluated before g or vice versa; thus if either f or g alters a variable on which the
other depends, x can depend on the order of evaluation
...

f

Similarly, the order in which function arguments are evaluated is not specified, so the
statement
printf("%d %d\n", ++n, power(2, n));

/* WRONG */

can produce different results with different compilers, depending on whether n is incremented
before power is called
...

`
'
In any expression involving side effects, there can be subtle dependencies on the order in
which variables taking part in the expression are updated
...
Compilers can interpret
this in different ways, and generate different answers depending on their interpretation
...
When side effects (assignment to
variables) take place within an expression is left to the discretion of the compiler, since the
best order depends strongly on machine architecture
...
)
The moral is that writing code that depends on order of evaluation is a bad programming
practice in any language
...


50

Chapter 3 - Control Flow
The control-flow of a language specify the order in which computations are performed
...


3
...
) becomes a statement when it is
followed by a semicolon, as in
x = 0;
i++;
printf(
...

Braces { and } are used to group declarations and statements together into a compound
statement, or block, so that they are syntactically equivalent to a single statement
...
(Variables can be declared inside any
block; we will talk about this in Chapter 4
...


3
...
Formally the syntax is
if (expression)
statement1
else
statement2
where the else part is

optional
...
If it is false (expression is zero) and if there is
an else part, statement2 is executed instead
...

The most obvious is writing
if (expression)

instead of

if (expression != 0)

Sometimes this is natural and clear; at other times it can be cryptic
...
This is resolved by associating the else with the closest previous
else-less if
...
If that isn'what you want,
t
braces must be used to force the proper association:
if (n > 0) {
if (a > b)

51
z = a;
}
else
z = b;

The ambiguity is especially pernicious in situations like this:
if (n > 0)
for (i = 0; i < n; i++)
if (s[i] > 0) {
printf("
...
This kind of bug can be hard to find; it' a
good idea to use braces when there are nested ifs
...

`
'

3
...
This sequence of if statements is
the most general way of writing a multi-way decision
...
As always, the code for each statement is either a single statement, or a group of
them in braces
...
Sometimes there is no explicit action for the default; in that case the
trailing
else
statement

can be omitted, or it may be used for error checking to catch an `impossible'condition
...
The elements of v must be in increasing order
...

Binary search first compares the input value x to the middle element of the array v
...
In either case, the next step is to compare x to the middle element of the selected

52
half
...

/* binsearch: find x in v[0] <= v[1] <=
...

Exercise 3-1
...
) Write a version with only one test inside the loop and
measure the difference in run-time
...
4 Switch
The switch statement is a multi-way decision that tests whether an expression matches one
of a number of constant integer values, and branches accordingly
...
If a
case matches the expression value, execution starts at that case
...
The case labeled default is executed if none of the other cases are satisfied
...
Cases and the default clause can occur in any order
...
else if
...
Here is the same program
with a switch:
#include ...
Because cases serve just as
labels, after the code for one case is done, execution falls through to the next unless you take
explicit action to escape
...
A
break statement can also be used to force an immediate exit from while, for, and do loops,
as will be discussed later in this chapter
...
On the positive side, it allows several cases to be
attached to a single action, as with the digits in this example
...
Falling through from
one case to another is not robust, being prone to disintegration when the program is modified
...

As a matter of good form, put a break after the last case (the default here) even though it'
s
logically unnecessary
...

Exercise 3-2
...
Use a switch
...


3
...
In
while (expression)
statement

the expression is evaluated
...
This cycle continues until expression becomes zero, at which point execution
resumes after statement
...
7
...
Most commonly, expr1
and expr3 are assignments or function calls and expr2 is a relational expression
...
If expr1 or expr3 is omitted,
it is simply dropped from the expansion
...

}

is an `infinite'loop, presumably to be broken by other means, such as a break or return
...
For example, in
while ((c = getchar()) == ' ' || c == '\n' || c = '\t')
;
/* skip white space characters */
there is no initialization or re-initialization, so the while is most natural
...
This is most obvious
in
for (i = 0; i < n; i++)

...
The analogy is not perfect, however, since the index variable i
retains its value when the loop terminates for any reason
...
Nonetheless,
it is bad style to force unrelated computations into the initialization and increment of a for,
which are better reserved for loop control operations
...
This one is slightly more general than the one in Chapter 2; it copes with optional
leading white space and an optional + or - sign
...
)
The structure of the program reflects the form of the input:
skip white space, if any
get sign, if any
get integer part and convert it
Each step does its part, and leaves things in a clean state for the next
...

#include ...

The advantages of keeping loop control centralized are even more obvious when there are
several nested loops
...

The basic idea of this sorting algorithm, which was invented in 1959 by D
...
Shell, is that in
early stages, far-apart elements are compared, rather than adjacent ones as in simpler
interchange sorts
...
The interval between compared elements is gradually decreased to one,
at which point the sort effectively becomes an adjacent interchange method
...
v[n-1] into increasing order */
void shellsort(int v[], int n)
{
int gap, i, j, temp;
for (gap = n/2; gap > 0; gap /= 2)
for (i = gap; i < n; i++)
for (j=i-gap; j>=0 && v[j]>v[j+gap]; j-=gap) {
temp = v[j];
v[j] = v[j+gap];
v[j+gap] = temp;
}
}

There are three nested loops
...
The middle loop
steps along the elements
...
Since gap is eventually reduced to one, all
elements are eventually ordered correctly
...

,
One final C operator is the comma `,' which most often finds use in the for statement
...
Thus in a for statement, it is possible to
place multiple expressions in the various parts, for example to process two indices in parallel
...

#include ...
, are not comma
operators, and do not guarantee left to right evaluation
...
The most suitable uses are for constructs strongly
related to each other, as in the for loop in reverse, and in macros where a multistep
computation has to be a single expression
...
Write a function expand(s1,s2) that expands shorthand notations like a-z in
the string s1 into the equivalent complete list abc
...
Allow for letters of either
case and digits, and be prepared to handle cases like a-b-c and a-z0-9 and -a-z
...


3
...
By contrast, the third loop in C, the do-while, tests at the bottom after making each pass
through the loop body; the body is always executed at least once
...
If it is true, statement is evaluated
again, and so on
...
Except for the
sense of the test, do-while is equivalent to the Pascal repeat-until statement
...
Nonetheless, from
time to time it is valuable, as in the following function itoa, which converts a number to a
character string (the inverse of atoi)
...
We have chosen to generate the string backwards, then reverse it
...
We also used braces around the single statement that
makes up the body of the do-while, even though they are unnecessary, so the hasty reader
will not mistake the while part for the beginning of a while loop
...
In a two' complement number representation, our version of itoa does not
s
handle the largest negative number, that is, the value of n equal to -(2wordsize-1)
...
Modify it to print that value correctly, regardless of the machine on which it runs
...
Write the function itob(n,s,b) that converts the integer n into a base b
character representation in the string s
...

Exercise 3-6
...
The third
argument is a minimum field width; the converted number must be padded with blanks on the
left if necessary to make it wide enough
...
7 Break and Continue

57
It is sometimes convenient to be able to exit from a loop other than by testing at the top or
bottom
...
A break causes the innermost enclosing loop or switch to be exited immediately
...

/* trim: remove trailing blanks, tabs, newlines */
int trim(char s[])
{
int n;
for (n = strlen(s)-1; n >= 0; n--)
if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
break;
s[n+1] = '\0';
return n;
}
strlen

returns the length of the string
...
The loop is broken when
one is found, or when n becomes negative (that is, when the entire string has been scanned)
...

The continue statement is related to break, but less often used; it causes the next iteration of
the enclosing for, while, or do loop to begin
...
The continue
statement applies only to loops, not to switch
...

As an example, this fragment processes only the non-negative elements in the array a;
negative values are skipped
...
/* do positive elements */
The continue statement is often used when the part of the loop

that follows is complicated,
so that reversing a test and indenting another level would nest the program too deeply
...
8 Goto and labels
C provides the infinitely-abusable goto statement, and labels to branch to
...

We have not used goto in this book
...
The most common is
to abandon processing in some deeply nested structure, such as breaking out of two or more
loops at once
...
Thus:
for (
...
) {

...

error:
/* clean up the mess */

58
This organization is handy if the error-handling code is non-trivial, and if errors can occur in
several places
...
It can be attached
to any statement in the same function as the goto
...

As another example, consider the problem of determining whether two arrays a and b have an
element in common
...

found:
/* got one: a[i] == b[j] */

...
For example, the array search becomes
found = 0;
for (i = 0; i < n && !found; i++)
for (j = 0; j < m && !found; j++)
if (a[i] == b[j])
found = 1;
if (found)
/* got one: a[i-1] == b[j-1] */

...


With a few exceptions like those cited here, code that relies on goto statements is generally
harder to understand and to maintain than code without gotos
...


59

Chapter 4 - Functions and Program
Structure
Functions break large computing tasks into smaller ones, and enable people to build on what
others have done instead of starting over from scratch
...

C has been designed to make functions efficient and easy to use; C programs generally
consist of many small functions rather than a few big ones
...
Source files may be compiled separately and loaded together, along with
previously compiled functions from libraries
...

Function declaration and definition is the area where the ANSI standard has made the most
changes to C
...
The syntax of function declaration also changes, so that
declarations and definitions match
...
Furthermore, when arguments are properly declared, appropriate
type coercions are performed automatically
...
Initialization is more general: automatic arrays
and structures may now be initialized
...
New preprocessor facilities include a more
complete set of conditional compilation directives, a way to create quoted strings from macro
arguments, and better control over the macro expansion process
...
1 Basics of Functions
To begin with, let us design and write a program to print each line of its input that contains a
particular `pattern' string of characters
...
) For example, searching for the pattern of letters `ould'in the set of lines
`
'
Ah Love! could you and I with Fate conspire
To grasp this sorry Scheme of Things entire,
Would not we shatter it to bits -- and then
Re-mould it nearer to the Heart's Desire!

will produce the output

Ah Love! could you and I with Fate conspire
Would not we shatter it to bits -- and then
Re-mould it nearer to the Heart's Desire!

The job falls neatly into three pieces:

while (there's another line)
if (the line contains the pattern)
print it

Although it' certainly possible to put the code for all of this in main, a better way is to use
s
the structure to advantage by making each part a separate function
...
And the pieces may even be useful in
other programs
...
This means we need only write a
routine to decide whether the line contains an occurrence of the pattern
...
Because C arrays
begin at position zero, indexes will be zero or positive, and so a negative value like -1 is
convenient for signaling failure
...
(The standard
library provides a function strstr that is similar to strindex, except that it returns a pointer
instead of an index
...
Here is the
whole thing, so you can see how the pieces fit together
...
We will return shortly to a
discussion of how to initialize character arrays, and in Chapter 5 will show how to make the
pattern a parameter that is set when the program is run
...

#include ...
A do-nothing function like this is sometimes useful
as a place holder during program development
...

A program is just a set of definitions of variables and functions
...
The functions can occur in any order in the source file, and the source program can
be split into multiple files, so long as no function is split
...
Any expression can follow return:
return expression;

The expression will be converted to the return type of the function if necessary
...

The calling function is free to ignore the returned value
...
Control also returns to
the caller with no value when execution `falls off the end'of the function by reaching the
`
'
closing right brace
...
In any case, if a function fails to return a value, its
`value'is certain to be garbage
...
This
value is available for use by the environment that called the program
The mechanics of how to compile and load a C program that resides on multiple source files
vary from one system to the next
...
Suppose that the three functions are stored in three files
called main
...
c, and strindex
...
Then the command
cc main
...
c strindex
...
o, getline
...
o, then loads them all into an executable file called a
...
If there is an error, say
in main
...
c getline
...
o
The cc command uses the `
...
o'naming
` '
` '

from object files
...
Write the function strindex(s,t) which returns the position of the rightmost
occurrence of t in s, or -1 if there is none
...
2 Functions Returning Non-integers

62
So far our examples of functions have returned either no value (void) or an int
...
To illustrate how to deal with
this, let us write and use the function atof(s), which converts the string s to its doubleprecision floating-point equivalent
...
It handles an optional sign and decimal point, and the presence or
absence of either part or fractional part
...
The standard library includes an
atof; the header ...

First, atof itself must declare the type of value it returns, since it is not int
...
h>
/* atof: convert string s to double */
double atof(char s[])
{
double val, power;
int i, sign;
for (i = 0; isspace(s[i]); i++) /* skip white space */
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (val = 0
...
0 * val + (s[i] - '0');
if (s[i] == '
...
0; isdigit(s[i]); i++) {
val = 10
...
One way to ensure this is to declare atof explicitly in the calling routine
...
h>
#define MAXLINE 100
/* rudimentary calculator */
main()
{
double sum, atof(char []);
char line[MAXLINE];
int getline(char line[], int max);
sum = 0;
while (getline(line, MAXLINE) > 0)
printf("\t%g\n", sum += atof(line));
return 0;
}

The declaration
double sum, atof(char []);

says that sum is a double variable, and that atof is a function that takes one char[]
argument and returns a double
...
If atof itself and the call to it
in main have inconsistent types in the same source file, the error will be detected by the
compiler
...

In the light of what we have said about how declarations must match definitions, this might
seem surprising
...
Furthermore, if a function
declaration does not include arguments, as in
double atof();

that too is taken to mean that nothing is to be assumed about the arguments of atof; all
parameter checking is turned off
...
But it' a bad idea to use it with
s
new C programs
...

Given atof, properly declared, we could write atoi (convert a string to int) in terms of it:
/* atoi: convert string s to integer using atof */
int atoi(char s[])
{
double atof(char s[]);
return (int) atof(s);
}

Notice the structure of the declarations and the return statement
...
Therefore, the value of
atof, a double, is converted automatically to int when it appears in this return, since the
function atoi returns an int
...
The cast states explicitly that the operation is
intended, and suppresses any warning
...
Extend atof to handle scientific notation of the form
123
...


4
...
The
adjective `external' used in contrast to `internal' which describes the arguments and
`
'is
`
'
,
variables defined inside functions
...
Functions themselves are always external,
because C does not allow functions to be defined inside other functions
...
(The standard calls this
property external linkage
...
We will see later how to

64
define external variables and functions that are visible only within a single source file
...
Any function may
access an external variable by referring to it by name, if the name has been declared
somehow
...
As pointed out in Chapter 1, however, this
reasoning should be applied with some caution, for it can have a bad effect on program
structure, and lead to programs with too many data connections between functions
...
Automatic
variables are internal to a function; they come into existence when the function is entered,
and disappear when it is left
...
Thus if two functions must share
some data, yet neither calls the other, it is often most convenient if the shared data is kept in
external variables rather than being passed in and out via arguments
...
The problem is to write a calculator program
that provides the operators +, -, * and /
...
(Reverse Polish notation is used by some pocket
calculators, and in languages like Forth and Postscript
...

The implementation is simple
...
In the example above, for instance, 1 and 2
are pushed, then replaced by their difference, -1
...
The product of -1 and 9, which is -9, replaces them on the stack
...

The structure of the program is thus a loop that performs the proper operation on each
operator and operand as it appears:
while (next operator or operand is not end-of-file indicator)
if (number)
push it
else if (operator)
pop operands
do operation
push result
else if (newline)
pop and print top of stack
else
error

The operation of pushing and popping a stack are trivial, but by the time error detection and
recovery are added, they are long enough that it is better to put each in a separate function
than to repeat the code throughout the whole program
...


65
The main design decision that has not yet been discussed is where the stack is, that is, which
routines access it directly
...
But main doesn' need to know
t
about the variables that control the stack; it only does push and pop operations
...

Translating this outline into code is easy enough
...
}

external variables for push and pop
void push( double f) {
...
}
int getop(char s[]) {
...

The function main is a loop containing a big switch on the type of operator or operand; this
is a more typical use of switch than the one shown in Section 3
...

#include ...
h>

/* for

#define MAXOP
#define NUMBER

/* max size of operand or operator */
/* signal that a number was found */

100
'0'

atof() */

int getop(char []);
void push(double);
double pop(void);
/* reverse Polish calculator */
main()
{
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':

66
op2 = pop();
if (op2 != 0
...
8g\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}

Because + and * are commutative operators, the order in which the popped operands are
combined is irrelevant, but for - and / the left and right operand must be distinguished
...
To guarantee the right
order, it is necessary to pop the first value into a temporary variable as we did in main
...
0;
}
}

A variable is external if it is defined outside of any function
...
But main itself does
not refer to the stack or stack position - the representation can be hidden
...
The task is easy
...
If the next character is not a digit or a
hexadecimal point, return it
...

#include ...
')
return c;
/* not a number */
i = 0;
if (isdigit(c))
/* collect integer part */
while (isdigit(s[++i] = c = getch()))
;
if (c == '
...
One instance is collecting characters that make
up a number: until the first non-digit is seen, the number is not complete
...

The problem would be solved if it were possible to `un-read'the unwanted character
...
Fortunately, it' easy to simulate
s
un-getting a character, by writing a pair of cooperating functions
...

How they work together is simple
...
getch reads from the buffer if there is anything else, and calls
getchar if the buffer is empty
...

Since the buffer and the index are shared by getch and ungetch and must retain their values
between calls, they must be external to both routines
...
We have used an array for the pushback, rather than a single
character, to illustrate a more general approach
...
Given the basic framework, it' straightforward to extend the calculator
...


68
Exercise 4-4
...
Add a command to clear the stack
...
Add access to library functions like sin, exp, and pow
...
h> in
Appendix B, Section 4
...
Add commands for handling variables
...
) Add a variable for the most recently printed value
...
Write a routine ungets(s) that will push back an entire string onto the input
...
Suppose that there will never be more than one character of pushback
...


getch

Exercise 4-9
...
Decide
what their properties ought to be if an EOF is pushed back, then implement your design
...
An alternate organization uses getline to read an entire input line; this makes
getch and ungetch unnecessary
...


4
...
Among the questions of interest are


How are declarations written so that variables are properly declared during
compilation?



How are declarations arranged so that all the pieces will be properly connected when
the program is loaded?



How are declarations organized so there is only one copy?



How are external variables initialized?

Let us discuss these topics by reorganizing the calculator program into several files
...

The scope of a name is the part of the program within which the name can be used
...
Local variables of the same name in different functions are unrelated
...

The scope of an external variable or a function lasts from the point at which it is declared to
the end of the file being compiled
...
}
int sp = 0;
double val[MAXVAL];
void push(double f) {
...
}

69
then the variables sp and val may be used in push and pop simply by naming them; no
further declarations are needed
...

On the other hand, if an external variable is to be referred to before it is defined, or if it is
defined in a different source file from the one where it is being used, then an extern
declaration is mandatory
...
A declaration announces the properties of a variable (primarily its type); a
definition also causes storage to be set aside
...
On the other
hand, the lines
extern int sp;
extern double val[];

declare for the rest of the source file that sp is an int and that val is a double array (whose
size is determined elsewhere), but they do not create the variables or reserve storage for them
...
(There may also be
extern declarations in the file containing the definition
...

Initialization of an external variable goes only with the definition
...
Then these
definitions and declarations would be necessary to tie them together:
in file1:
extern int sp;
extern double val[];
void push(double f) {
...
}

in file2:

int sp = 0;
double val[MAXVAL];
Because the extern declarations

in file1 lie ahead of and outside the function definitions,
they apply to all functions; one set of declarations suffices for all of file1
...


4
...
The main function would go in one file,
which we will call main
...
c;
getop goes into a third, getop
...
Finally, getch and ungetch go into a fourth file, getch
...


70
There is one more thing to worry about - the definitions and declarations shared among files
...
Accordingly, we will place this common material in a header
file, calc
...
(The #include line is described in Section
4
...
) The resulting program then looks like this:

There is a tradeoff between the desire that each file have access only to the information it
needs for its job and the practical reality that it is harder to maintain more header files
...
For a much larger program, more organization and more headers would be
needed
...
6 Static Variables
The variables sp and val in stack
...
c, are for the private use of
the functions in their respective source files, and are not meant to be accessed by anything
else
...
External static thus provides a way
to hide names like buf and bufp in the getch-ungetch combination, which must be external
so they can be shared, yet which should not be visible to users of getch and ungetch
...
If the
two routines and the two variables are compiled in one file, as in
static char buf[BUFSIZE];
static int bufp = 0;

/* buffer for ungetch */
/* next free position in buf */

int getch(void) {
...
}

then no other routine will be able to access buf and bufp, and those names will not conflict
with the same names in other files of the same program
...

The external static declaration is most often used for variables, but it can be applied to
functions as well
...
If a function is declared static, however, its name is invisible outside of the file in
which it is declared
...
Internal static variables
are local to a particular function just as automatic variables are, but unlike automatics, they
remain in existence rather than coming and going each time the function is activated
...

Exercise 4-11
...
Hint: use an internal
t
static variable
...
7 Register Variables
A register declaration advises the compiler that the variable in question will be heavily
used
...
But compilers are free to ignore the advice
...
The register

declaration can only be applied to automatic variables and to the
formal parameters of a function
...

}

In practice, there are restrictions on register variables, reflecting the realities of underlying
hardware
...
Excess register declarations are harmless, however, since the word
register is ignored for excess or disallowed declarations
...
The specific restrictions on number and types of
register variables vary from machine to machine
...
8 Block Structure

72
C is not a block-structured language in the sense of Pascal or similar languages, because
functions may not be defined within other functions
...
Declarations of variables (including
initializations) may follow the left brace that introduces any compound statement, not just the
one that begins a function
...
For example,
in
if (n > 0) {
int i; /* declare a new i */
for (i = 0; i < n; i++)

...
An automatic variable declared and initialized in a block is initialized each time the
block is entered
...
Given the declarations
int x;
int y;
f(double x)
{
double y;
}

then within the function f, occurrences of x refer to the parameter, which is a double; outside
f, they refer to the external int
...

As a matter of style, it' best to avoid variable names that conceal names in an outer scope;
s
the potential for confusion and error is too great
...
9 Initialization
Initialization has been mentioned in passing many times so far, but always peripherally to
some other topic
...

In the absence of explicit initialization, external and static variables are guaranteed to be
initialized to zero; automatic and register variables have undefined (i
...
, garbage) initial
values
...
For
automatic and register variables, the initializer is not restricted to being a constant: it may be
any expression involving previously defined values, even function calls
...
3 could be written as
int binsearch(int x, int v[], int n)
{
int low = 0;
int high = n - 1;
int mid;

73

...

Which form to prefer is largely a matter of taste
...

An array may be initialized by following its declaration with a list of initializers enclosed in
braces and separated by commas
...

If there are fewer initializers for an array than the specified size, the others will be zero for
external, static and automatic variables
...
There is no
way to specify repetition of an initializer, nor to initialize an element in the middle of an array
without supplying all the preceding values as well
...


4
...
Consider printing a number as a character string
...

There are two solutions to this problem
...
6
...
Again, this version can fail on the largest negative
number
...
h>
/* printd: print n in decimal */
void printd(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n / 10)
printd(n / 10);
putchar(n % 10 + '0');
}

74
When a function calls itself recursively, each invocation gets a fresh set of all the automatic
variables, independent of the previous set
...
It passes 12 to a second printd, which in turn passes 1 to a third
...
That printd prints 2, then
returns to the first level
...

Another good example of recursion is quicksort, a sorting algorithm developed by C
...
R
...
Given an array, one element is chosen and the others partitioned in two
subsets - those less than the partition element and those greater than or equal to it
...
When a subset has fewer than two
elements, it doesn'need any sorting; this stops the recursion
...
We use the
s
middle element of each subarray for partitioning
...
v[right] into increasing order */
void qsort(int v[], int left, int right)
{
int i, last;
void swap(int v[], int i, int j);
if (left >= right) /* do nothing if array contains */
return;
/* fewer than two elements */
swap(v, left, (left + right)/2); /* move partition elem */
last = left;
/* to v[0] */
for (i = left + 1; i <= right; i++) /* partition */
if (v[i] < v[left])
swap(v, ++last, i);
swap(v, left, last);
/* restore partition elem */
qsort(v, left, last-1);
qsort(v, last+1, right);
}

We moved the swapping operation into a separate function swap because it occurs three times
in qsort
...

Recursion may provide no saving in storage, since somewhere a stack of the values being
processed must be maintained
...
But recursive code is more compact, and
often much easier to write and understand than the non-recursive equivalent
...
6
...
Adapt the ideas of printd to write a recursive version of itoa; that is, convert
an integer into a string by calling a recursive routine
...
Write a recursive version of the function reverse(s), which reverses the
string s in place
...
11 The C Preprocessor
C provides certain language facilities by means of a preprocessor, which is conceptionally a
separate first step in compilation
...
Other features described in this section include conditional
compilation and macros with arguments
...
11
...
Any source line of the form
or

#include "filename"
#include

is replaced by the contents of the file filename
...
An
included file may itself contain #include lines
...
h>
...
)
#include is the preferred way to tie the declarations together for a large program
...
Naturally, when an
included file is changed, all files that depend on it must be recompiled
...
11
...
The name in a #define has the same form as a
variable name; the replacement text is arbitrary
...
The scope of a name defined with #define is from its point of
definition to the end of the source file being compiled
...
Substitutions are made only for tokens, and do not take place within quoted
strings
...

Any name may be defined with any replacement text
...


It is also possible to define macros with arguments, so the replacement text can be different
for different calls of the macro
...
Each occurrence
of a formal parameter (here A or B) will be replaced by the corresponding actual argument
...

If you examine the expansion of max, you will notice some pitfalls
...
For instance
max(i++, j++)

/* WRONG */

will increment the larger twice
...


/* WRONG */

Nonetheless, macros are valuable
...
h>, in which
and putchar are often defined as macros to avoid the run-time overhead of a
function call per character processed
...
h> are also usually
implemented as macros
...
}

Formal parameters are not replaced within quoted strings
...
This can be combined with string
concatenation to make, for example, a debugging print macro:
#define

dprint(expr)

When this is invoked, as in

printf(#expr " = %g\n", expr)

dprint(x/y)

the macro is expanded into
printf("x/y" " = &g\n", x/y);

and the strings are concatenated, so the effect is
printf("x/y = &g\n", x/y);

Within the actual argument, each " is replaced by \" and each \ by \\, so the result is a legal
string constant
...
If a parameter in the replacement text is adjacent to a ##, the parameter is replaced
by the actual argument, the ## and surrounding white space are removed, and the result is rescanned
...


The rules for nested uses of ## are arcane; further details may be found in Appendix A
...
Define a macro swap(t,x,y) that interchanges two arguments of type t
...
)

4
...
3 Conditional Inclusion

77
It is possible to control preprocessing itself with conditional statements that are evaluated
during preprocessing
...

The #if line evaluates a constant integer expression (which may not include sizeof, casts, or
enum constants)
...
(The preprocessor statement #elif is like else-if
...

For example, to make sure that the contents of a file hdr
...
h go here */
#endif

The first inclusion of hdr
...
A similar style can be used to avoid including files
multiple times
...

This sequence tests the name SYSTEM to decide which version of a header to include:
#if SYSTEM == SYSV
#define HDR "sysv
...
h"
#elif SYSTEM == MSDOS
#define HDR "msdos
...
h"
#endif
#include HDR
The #ifdef and #ifndef lines are specialized forms
first example of #if above could have been written
#ifndef HDR
#define HDR
/* contents of hdr
...
The

78

Chapter 5 - Pointers and Arrays
A pointer is a variable that contains the address of a variable
...

Pointers and arrays are closely related; this chapter also explores this relationship and shows
how to exploit it
...
This is certainly true when they are used carelessly, and it is easy to
create pointers that point somewhere unexpected
...
This is the aspect that we will try to illustrate
...
In addition, the type void * (pointer to void) replaces char * as
the proper type for a generic pointer
...
1 Pointers and Addresses
Let us begin with a simplified picture of how memory is organized
...
One common situation is that any byte can be a char, a
pair of one-byte cells can be treated as a short integer, and four adjacent bytes form a long
...
So if c is a char and
p is a pointer that points to it, we could represent the situation this way:

The unary operator & gives the address of an object, so the statement
p = &c;

assigns the address of c to the variable p, and p is said to `point to'c
...
It cannot be applied to
expressions, constants, or register variables
...
Suppose that x and y are integers and ip is a
pointer to int
...

ve

The declaration of the pointer ip,

79
is intended as a mnemonic; it says that the expression *ip is an int
...
This reasoning applies to function declarations as well
...


have values of double, and that the argument of

You should also note the implication that a pointer is constrained to point to a particular kind
of object: every pointer points to a specific data type
...
We' come back
'
ll
to it in Section 5
...
)
If ip points to the integer x, then *ip can occur in any context where x could, so
*ip = *ip + 10;
increments *ip by 10
...

Finally, since pointers are variables, they can be used without dereferencing
...


5
...
For instance, a sorting routine might exchange two
out-of-order arguments with a function called swap
...

t
The function above swaps copies of a and b
...
In swap itself, the
parameters are declared as pointers, and the operands are accessed indirectly through them
...
As an example, consider a function getint that performs free-format input conversion by
breaking a stream of characters into integer values, one integer per call
...
These values have
to be passed back by separate paths, for no matter what value is used for EOF, that could also
be the value of an input integer
...
This is the
scheme used by scanf as well; see Section 7
...

The following loop fills an array with integers by calls to getint:

81
int n, array[SIZE], getint(int *);
for (n = 0; n < SIZE && getint(&array[n]) != EOF; n++)
;
Each call sets array[n] to the next integer found in the input and increments n
...
Otherwise there is no way for getint

to communicate the converted integer back to the caller
...

#include ...
We have also used getch and
ungetch (described in Section 4
...

Exercise 5-1
...
Fix it to push such a character back on the input
...
Write getfloat, the floating-point analog of getint
...
3 Pointers and Arrays
In C, there is a strong relationship between pointers and arrays, strong enough that pointers
and arrays should be discussed simultaneously
...
The pointer version will in general be faster but,
at least to the uninitiated, somewhat harder to understand
...
,a[9]
...
If pa is a pointer to an integer,
declared as
int *pa;

then the assignment
pa = &a[0];

sets pa to point to element zero of a; that is, pa contains the address of a[0]
...

If pa points to a particular element of an array, then by definition pa+1 points to the next
element, pa+i points i elements after pa, and pa-i points i elements before
...


83
These remarks are true regardless of the type or size of the variables in the array a
...

The correspondence between indexing and pointer arithmetic is very close
...

Thus after the assignment
pa = &a[0];
pa and a have identical

values
...
In evaluating a[i], C converts it to *(a+i) immediately; the two forms are
equivalent
...
As the other side
of this coin, if pa is a pointer, expressions might use it with a subscript; pa[i] is identical to
*(pa+i)
...

There is one difference between an array name and a pointer that must be kept in mind
...
But an array name is not a variable;
constructions like a=pa and a++ are illegal
...
Within the called function, this argument is a local variable, and so an array name
parameter is a pointer, that is, a variable containing an address
...

/* strlen: return length of string s */
int strlen(char *s)
{
int n;
for (n = 0; *s != '\0', s++)
n++;
return n;
}

Since s is a pointer, incrementing it is perfectly legal; s++ has no effect on the character
string in the function that called strlen, but merely increments strlen' private copy of the
s
pointer
...


/* string constant */
/* char array[100]; */
/* char *ptr; */

As formal parameters in a function definition,
and

char s[];
char *s;

are equivalent; we prefer the latter because it says more explicitly that the variable is a
pointer
...
It
can even use both notations if it seems appropriate and clear
...
For example, if a is an array,
and

f(&a[2])
f(a+2)

both pass to the function f the address of the subarray that starts at a[2]
...
}
f(int *arr) {
...

If one is sure that the elements exist, it is also possible to index backwards in an array; p[-1],
p[-2], and so on are syntactically legal, and refer to the elements that immediately precede
p[0]
...


5
...
These
and similar constructions are the simples forms of pointer or address arithmetic
...
Let us illustrate by
writing a rudimentary storage allocator
...
The first, alloc(n), returns a
pointer to n consecutive character positions, which can be used by the caller of alloc for
storing characters
...
The routines are `rudimentary'because the calls to afree must be made in the
`
'
opposite order to the calls made on alloc
...
The standard library provides analogous functions called
malloc and free that have no such restrictions; in Section 8
...

The easiest implementation is to have alloc hand out pieces of a large character array that
we will call allocbuf
...
Since they deal in pointers,
not array indices, no other routine need know the name of the array, which can be declared
static in the source file containing alloc and afree, and thus be invisible outside it
...

The other information needed is how much of allocbuf has been used
...
When alloc is asked for n characters, it
checks to see if there is enough room left in allocbuf
...
e
...
If there is no room, alloc returns zero
...


85

#define ALLOCSIZE 10000 /* size of available space */
static char allocbuf[ALLOCSIZE]; /* storage for alloc */
static char *allocp = allocbuf; /* next free position */
char *alloc(int n)
/* return pointer to n characters */
{
if (allocbuf + ALLOCSIZE - allocp >= n) { /* it fits */
allocp += n;
return allocp - n; /* old p */
} else
/* not enough room */
return 0;
}
void afree(char *p) /* free storage pointed to by p */
{
if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
allocp = p;
}

In general a pointer can be initialized just as any other variable can, though normally the only
meaningful values are zero or an expression involving the address of previously defined data
of appropriate type
...
This could also have been
written
static char *allocp = &allocbuf[0];

since the array name is the address of the zeroth element
...
If there is, the new value of
s
allocp would be at most one beyond the end of allocbuf
...
If not, alloc must return some signal that there is no space left
...

Pointers and integers are not interchangeable
...
The
symbolic constant NULL is often used in place of zero, as a mnemonic to indicate more clearly

86
that this is a special value for a pointer
...
h>
...

Tests like
if (allocbuf + ALLOCSIZE - allocp >= n) {

and

/* it fits */

if (p >= allocbuf && p < allocbuf + ALLOCSIZE)

show several important facets of pointer arithmetic
...
If p and q point to members of the same array, then relations like ==,
!=, <, >=, etc
...
For example,
p < q

is true if p points to an earlier element of the array than q does
...
But the behavior is undefined for
arithmetic or comparisons with pointers that do not point to members of the same array
...
)
Second, we have already observed that a pointer and an integer may be added or subtracted
...
This is true
regardless of the kind of object p points to; n is scaled according to the size of the objects p
points to, which is determined by the declaration of p
...

Pointer subtraction is also valid: if p and q point to elements of the same array, and pq-p+1 is the number of elements from p to q inclusive
...
In the
while loop, each character in turn is examined until the '\0' at the end is seen
...
(The number of characters in
the string could be too large to store in an int
...
h> defines a type
ptrdiff_t that is large enough to hold the signed difference of two pointer values
...
size_t is the unsigned integer type returned by the sizeof
operator
...

Thus we could write another version of alloc that maintains floats instead of chars, merely
by changing char to float throughout alloc and afree
...


87
The valid pointer operations are assignment of pointers of the same type, adding or
subtracting a pointer and an integer, subtracting or comparing two pointers to members of the
same array, and assigning or comparing to zero
...
It is not
legal to add two pointers, or to multiply or divide or shift or mask them, or to add float or
double to them, or even, except for void *, to assign a pointer of one type to a pointer of
another type without a cast
...
5 Character Pointers and Functions
A string constant, written as
"I am a string"

is an array of characters
...
The length in storage is thus one more than
the number of characters between the double quotes
...
That is, a string
constant is accessed by a pointer to its first element
...
If pmessage is declared as
char *pmessage;

then the statement

pmessage = "now is the time";

assigns to pmessage a pointer to the character array
...
C does not provide any operators for processing an entire string of characters as
a unit
...
Individual characters within the array may be changed but amessage will always
refer to the same storage
...


We will illustrate more aspects of pointers and arrays by studying versions of two useful
functions adapted from the standard library
...
It would be nice just to say s=t but this copies the pointer, not the
characters
...
The array version first:
/* strcpy:

copy t to s; array subscript version */

88
void strcpy(char *s, char *t)
{
int i;
i = 0;
while ((s[i] = t[i]) != '\0')
i++;
}

For contrast, here is a version of strcpy with pointers:
/* strcpy: copy t to s; pointer version */
void strcpy(char *s, char *t)
{
int i;
i = 0;
while ((*s = *t) != '\0') {
s++;
t++;
}
}

Because arguments are passed by value, strcpy can use the parameters s and t in any way it
pleases
...

In practice, strcpy would not be written as we showed it above
...
The value of *t++ is the
character that t pointed to before t was incremented; the postfix ++ doesn' change t until
t
after this character has been fetched
...
This character is also the value that is compared against
'\0' to control the loop
...


As the final abbreviation, observe that a comparison against '\0' is redundant, since the
question is merely whether the expression is zero
...

The strcpy in the standard library ( ...

The second routine that we will examine is strcmp(s,t), which compares the character
strings s and t, and returns negative, zero or positive if s is lexicographically less than, equal
to, or greater than t
...

/* strcmp:

return <0 if s0 if s>t */

89
int strcmp(char *s, char *t)
{
int i;
for (i = 0; s[i] == t[i]; i++)
if (s[i] == '\0')
return 0;
return s[i] - t[i];
}

The pointer version of strcmp:
/* strcmp: return <0 if s0 if s>t */
int strcmp(char *s, char *t)
{
for ( ; *s == *t; s++, t++)
if (*s == '\0')
return 0;
return *s - *t;
}
Since ++ and -- are either prefix or postfix operators, other combinations

occur, although less frequently
...
In fact, the pair of expressions
*p++ = val;
val = *--p;

/* push val onto stack */
/* pop top of stack into val */

are the standard idiom for pushing and popping a stack; see Section 4
...

The header ...

Exercise 5-3
...

Exercise 5-4
...

Exercise 5-5
...
For example,
strncpy(s,t,n) copies at most n characters of t to s
...

Exercise 5-6
...
Good possibilities include getline (Chapters 1 and 4), atoi, itoa,
and their variants (Chapters 2, 3, and 4), reverse (Chapter 3), and strindex and getop
(Chapter 4)
...
6 Pointer Arrays; Pointers to Pointers
Since pointers are variables themselves, they can be stored in arrays just as other variables
can
...

In Chapter 3, we presented a Shell sort function that would sort an array of integers, and in
Chapter 4 we improved on it with a quicksort
...
We need a data representation
t
that will cope efficiently and conveniently with variable-length text lines
...
If the lines to be sorted are stored end-to-end in one
long character array, then each line can be accessed by a pointer to its first character
...
Two lines can be compared by passing their
pointers to strcmp
...


This eliminates the twin problems of complicated storage management and high overhead
that would go with moving the lines themselves
...
Let us defer the sorting step for a moment,
and concentrate on the data structure and the input and output
...
It will also have to count the number of input lines, since that
information is needed for sorting and printing
...

The output routine only has to print the lines in the order in which they appear in the array of
pointers
...
h>
#include ...
9
...
That is, lineptr[i] is a character pointer, and *lineptr[i] is the character it points
to, the first character of the i-th saved text line
...


it to the next line pointer

With input and output under control, we can proceed to sorting
...
The algorithm remains the same, which gives us some
confidence that it will still work
...
v[right] into increasing order */
void qsort(char *v[], int left, int right)
{
int i, last;
void swap(char *v[], int i, int j);
if (left >= right) /* do nothing if array contains */
return;
/* fewer than two elements */
swap(v, left, (left + right)/2);

92
last = left;
for (i = left+1; i <= right; i++)
if (strcmp(v[i], v[left]) < 0)
swap(v, ++last, i);
swap(v, left, last);
qsort(v, left, last-1);
qsort(v, last+1, right);
}

Similarly, the swap routine needs only trivial changes:
/* swap: interchange v[i] and v[j] */
void swap(char *v[], int i, int j)
{
char *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}

Since any individual element of v (alias lineptr) is a character pointer, temp must be also,
so one can be copied to the other
...
Rewrite readlines to store lines in an array supplied by main, rather than
calling alloc to maintain storage
...
7 Multi-dimensional Arrays
C provides rectangular multi-dimensional arrays, although in practice they are much less used
than arrays of pointers
...

Consider the problem of date conversion, from day of the month to day of the year and vice
versa
...
Let us define two functions to do the conversions: day_of_year converts the month and
day into the day of the year, and month_day converts the day of the year into the month and
day
...

These functions both need the same information, a table of the number of days in each month
(`thirty days hath September
...

and non-leap years, it' easier to separate them into two rows of a two-dimensional array than
s
to keep track of what happens to February during computation
...

The array daytab has to be external to both day_of_year and month_day, so they can both
use it
...

daytab is the first two-dimensional array we have dealt with
...
Hence subscripts are
written as
daytab[i][j]

/* [row][col] */

rather than

daytab[i,j]

/* WRONG */

Other than this notational distinction, a two-dimensional array can be treated in much the
same way as in other languages
...

An array is initialized by a list of initializers in braces; each row of a two-dimensional array is
initialized by a corresponding sub-list
...
Since space is not at a
premium here, this is clearer than adjusting the indices
...
In
this particular case, it is a pointer to objects that are arrays of 13 ints
...
}

It could also be

f(int daytab[][13]) {
...
}

which says that the parameter is a pointer to an array of 13 integers
...
Without parentheses, the
declaration
int *daytab[13]

is an array of 13 pointers to integers
...

Section 5
...

Exercise 5-8
...
Remedy this defect
...
8 Initialization of Pointer Arrays

94
Consider the problem of writing a function month_name(n), which returns a pointer to a
character string containing the name of the n-th month
...
month_name contains a private array of character strings, and returns a
pointer to the proper one when called
...

The syntax is similar to previous initializations:
/* month_name: return name of n-th month */
char *month_name(int n)
{
static char *name[] = {
"Illegal month",
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
return (n < 1 || n > 12) ? name[0] : name[n];
}

The declaration of name, which is an array of character pointers, is the same as lineptr in
the sorting example
...
The characters of the i-th string are placed somewhere,
and a pointer to them is stored in name[i]
...


5
...
Multi-dimensional Arrays
Newcomers to C are sometimes confused about the difference between a two-dimensional
array and an array of pointers, such as name in the example above
...
But a is a
true two-dimensional array: 200 int-sized locations have been set aside, and the conventional
rectangular subscript calculation 20 * row +col is used to find the element a[row,col]
...
Assuming that each
element of b does point to a twenty-element array, then there will be 200 ints set aside, plus
ten cells for the pointers
...
That is, each element of b need not point to a twentyelement vector; some may point to two elements, some to fifty, and some to none at all
...
Compare the declaration and picture for an array of pointers:
char *name[] = { "Illegal month", "Jan", "Feb", "Mar" };

95
with those for a two-dimensional array:
char aname[][15] = { "Illegal month", "Jan", "Feb", "Mar" };

Exercise 5-9
...


5
...
When main is called, it is called with two arguments
...
We customarily use
multiple levels of pointers to manipulate these character strings
...
That is, the command
echo hello, world

prints the output

hello, world

By convention, argv[0] is the name by which the program was invoked, so argc is at least 1
...
In the example
above, argc is 3, and argv[0], argv[1], and argv[2] are "echo", "hello,", and "world"
respectively
...


The first version of echo treats argv as an array of character pointers:
#include ...
This next variant is based on incrementing argv, which is a pointer to pointer
to char, while argc is counted down:
#include ...
Each successive
increment moves it along to the next argument; *argv is then the pointer to that argument
...


Alternatively, we could write the printf statement as
printf((argc > 1) ? "%s " : "%s", *++argv);
This shows that the format argument of printf can be an

expression too
...
1
...
Following the lead of the UNIX program grep, let us enhance
the program so the pattern to be matched is specified by the first argument on the command
line
...
h>
#include ...
It is declared in ...

The model can now be elaborated to illustrate further pointer constructions
...
One says `print all the lines except those that match the
`
pattern;'the second says `precede each printed line by its line number
...
If we choose -x (for `except' to
`
'
)
signal the inversion, and -n (`number' to request line numbering, then the command
`
'
)
find -x -npattern

will print each line that doesn'match the pattern, preceded by its line number
...
Furthermore, it is convenient for
users if option arguments can be combined, as in
find -nx pattern

Here is the program:

#include ...
h>
#define MAXLINE 1000
int getline(char *line, int max);
/* find: print lines that match pattern from 1st arg */
main(int argc, char *argv[])
{
char line[MAXLINE];
long lineno = 0;
int c, except = 0, number = 0, found = 0;
while (--argc > 0 && (*++argv)[0] == '-')
while (c = *++argv[0])
switch (c) {
case 'x':
except = 1;
break;
case 'n':
number = 1;
break;
default:
printf("find: illegal option %c\n", c);
argc = 0;
found = -1;
break;
}
if (argc != 1)
printf("Usage: find -x -n pattern\n");
else
while (getline(line, MAXLINE) > 0) {
lineno++;
if ((strstr(line, *argv) != NULL) != except) {
if (number)
printf("%ld:", lineno);
printf("%s", line);
found++;
}
}
return found;
}
argc

is decremented and argv is incremented before each optional argument
...
Thus argc should be 1 and *argv should point at the pattern
...

(An alternate valid form would be **++argv
...
In
fact, that is what we have used in the inner loop, where the task is to walk along a specific

98
argument string
...

Exercise 5-10
...
For example,
expr 2 3 4 + *

evaluates 2 * (3+4)
...
Modify the program entab and detab (written as exercises in Chapter 1) to
accept a list of tab stops as arguments
...

Exercise 5-12
...
Choose convenient (for the user)
default behavior
...
Write the program tail, which prints the last n lines of its input
...
The program should behave rationally no matter how unreasonable the
input or the value of n
...
6, not in a two-dimensional array of
fixed size
...
11 Pointers to Functions
In C, a function itself is not a variable, but it is possible to define pointers to functions, which
can be assigned, placed in arrays, passed to functions, returned by functions, and so on
...

A sort often consists of three parts - a comparison that determines the ordering of any pair of
objects, an exchange that reverses their order, and a sorting algorithm that makes
comparisons and exchanges until the objects are in order
...
This is the approach
taken in our new sort
...
These functions are declared ahead of main and
a pointer to the appropriate one is passed to qsort
...

#include ...
h>
#define MAXLINES 5000
char *lineptr[MAXLINES];

/* max #lines to be sorted */
/* pointers to text lines */

int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);

99
void qsort(void *lineptr[], int left, int right,
int (*comp)(void *, void *));
int numcmp(char *, char *);
/* sort input lines */
main(int argc, char *argv[])
{
int nlines;
/* number of input lines read */
int numeric = 0;
/* 1 if numeric sort */
if (argc > 1 && strcmp(argv[1], "-n") == 0)
numeric = 1;
if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qsort((void**) lineptr, 0, nlines-1,
(int (*)(void*,void*))(numeric ? numcmp : strcmp));
writelines(lineptr, nlines);
return 0;
} else {
printf("input too big to sort\n");
return 1;
}
}

In the call to qsort, strcmp and numcmp are addresses of functions
...

We have written qsort so it can process any data type, not just character strings
...
The generic pointer type void * is used for the pointer
arguments
...
The elaborate cast of the function
argument casts the arguments of the comparison function
...

/* qsort: sort v[left]
...
The fourth parameter of qsort is
int (*comp)(void *, void *)

which says that comp is a pointer to a function that has two void * arguments and returns an
int
...
The parentheses are needed so the components are correctly associated;
without them,
int *comp(void *, void *)

/* WRONG */

says that comp is a function returning a pointer to an int, which is very different
...
Here is numcmp, which
compares two strings on a leading numeric value, computed by calling atof:
#include ...

void swap(void *v[],
{
void *temp;

int i, int j;)

temp = v[i];
v[i] = v[j];
v[j] = temp;
}

A variety of other options can be added to the sorting program; some make challenging
exercises
...
Modify the sort program to handle a -r flag, which indicates sorting in
reverse (decreasing) order
...

Exercise 5-15
...

Exercise 5-16
...
Make sure it works in conjunction with -f
...
Add a field-searching capability, so sorting may bee done on fields within
lines, each field sorted according to an independent set of options
...
)

5
...
The syntax is an attempt to make the declaration and the use agree; it
works well for simple cases, but it can be confusing for the harder ones, because declarations
cannot be read left to right, and because parentheses are over-used
...


than (), so

Although truly complicated declarations rarely arise in practice, it is important to know how
to understand them, and, if necessary, how to create them
...
7
...
The word description reads left to right
...
It converts a C declaration into a word description, as in
these examples:
char **argv
argv: pointer to char
int (*daytab)[13]
daytab: pointer to array[13] of int
int *daytab[13]
daytab: array[13] of pointer to int
void *comp()
comp: function returning pointer to void
void (*comp)()
comp: pointer to function returning void
char (*(*x())[])()
x: function returning pointer to array[] of
pointer to function returning char
char (*(*x[3])())[5]
x: array[3] of pointer to function returning
pointer to array[5] of char
dcl is based on the grammar that specifies a declarator, which

Appendix A, Section 8
...

parenthesized dcl, or a direct-dcl followed by parentheses, or a direct-dcl followed by
brackets with an optional size
...
For instance, consider this declarator:
(*pfa[])()
pfa will be identified as a name
Then *pfa[] is recognized as a

and thus as a direct-dcl
...

dcl, so (*pfa[]) is a direct-dcl
...
We can also illustrate the parse with a tree like this (where directdcl has been abbreviated to dir-dcl):

102

The heart of the dcl program is a pair of functions, dcl and dirdcl, that parse a declaration
according to this grammar
...

/* dcl: parse a declarator */
void dcl(void)
{
int ns;
for (ns = 0; gettoken() == '*'; ) /* count *'s */
ns++;
dirdcl();
while (ns-- > 0)
strcat(out, " pointer to");
}
/* dirdcl: parse a direct declarator */
void dirdcl(void)
{
int type;
if (tokentype == '(') {
/* ( dcl ) */
dcl();
if (tokentype != ')')
printf("error: missing )\n");
} else if (tokentype == NAME) /* variable name */
strcpy(name, token);
else
printf("error: expected name or (dcl)\n");
while ((type=gettoken()) == PARENS || type == BRACKETS)

103
if (type == PARENS)
strcat(out, " function returning");
else {
strcat(out, " array");
strcat(out, token);
strcat(out, " of");
}
}

Since the programs are intended to be illustrative, not bullet-proof, there are significant
restrictions on dcl
...
It does not handle
argument types in functions, or qualifiers like const
...
It doesn'do
t
much error recovery, so invalid declarations will also confuse it
...

Here are the global variables and the main routine:
#include ...
h>
#include ...
*/

main() /* convert declaration to words */
{
while (gettoken() != EOF) {
/* 1st token on line */
strcpy(datatype, token); /* is the datatype */
out[0] = '\0';
dcl();
/* parse rest of line */
if (tokentype != '\n')
printf("syntax error\n");
printf("%s: %s %s\n", name, out, datatype);
}
return 0;
}
The function gettoken skips blanks and tabs, then finds the next token

in the input; a
`token'is a name, a pair of parentheses, a pair of brackets perhaps including a number, or
`
'
any other single character
...


Going in the other direction is easier, especially if we do not worry about generating
redundant parentheses
...
undcl also uses the same
external variables as dcl does
...
Make dcl recover from input errors
...
Modify undcl so that it does not add redundant parentheses to declarations
...
Expand dcl to handle declarations with function argument types, qualifiers
like const, and so on
...
(Structures are called `records'
`
'in
some languages, notably Pascal
...

One traditional example of a structure is the payroll record: an employee is described by a set
of attributes such as name, address, social security number, salary, etc
...

Another example, more typical for C, comes from graphics: a point is a pair of coordinate, a
rectangle is a pair of points, and so on
...
This has been
supported by most compilers for many years, but the properties are now precisely defined
...


6
...
The basic object is a point, which we will
assume has an x coordinate and a y coordinate, both integers
...
An optional name called a structure tag may follow the word struct (as
with point here)
...

The variables named in a structure are called members
...
e
...
Furthermore, the same member names may occur in
different structures, although as a matter of style one would normally use the same names
only for closely related objects
...
The right brace that terminates the list of members may
be followed by a list of variables, just as for any basic type
...
} x, y, z;

is syntactically analogous to
int x, y, z;

in the sense that each statement declares x, y and z to be variables of the named type and
causes space to be set aside for them
...
If the declaration is tagged, however, the tag can
be used later in definitions of instances of the structure
...
A structure can be
initialized by following its definition with a list of initializers, each a constant expression, for
the members:
struct maxpt = { 320, 200 };

An automatic structure may also be initialized by assignment or by calling a function that
returns a structure of the right type
...
member
The structure member operator `
...
To
`'
print the coordinates of the point pt, for instance,
printf("%d,%d", pt
...
y);

or to compute the distance from the origin (0,0) to pt,
double dist, sqrt(double);
dist = sqrt((double)pt
...
x + (double)pt
...
y);

Structures can be nested
...
pt1
...
If we declare screen as

107
refers to the x coordinate of the pt1 member of screen
...
2 Structures and Functions
The only legal operations on a structure are copying it or assigning to it as a unit, taking its
address with &, and accessing its members
...
Structures may not be compared
...

Let us investigate structures by writing some functions to manipulate points and rectangles
...
Each has its good points and bad points
...
x = x;
temp
...

makepoint can now be used to initialize any structure dynamically, or to provide structure
arguments to a function:
struct rect screen;
struct point middle;
struct point makepoint(int, int);
screen
...
pt2 = makepoint(XMAX, YMAX);
middle = makepoint((screen
...
x + screen
...
x)/2,
(screen
...
y + screen
...
y)/2);

The next step is a set of functions to do arithmetic on points
...
x += p2
...
y += p2
...
We incremented the components
in p1 rather than using an explicit temporary variable to emphasize that structure parameters
are passed by value like any others
...
x >= r
...
x
&& p
...
pt1
...
x < r
...
x
&& p
...
pt2
...
The following function returns a rectangle guaranteed to be in
canonical form:
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
/* canonrect: canonicalize coordinates of rectangle */
struct rect canonrect(struct rect r)
{
struct rect temp;
temp
...
x =
temp
...
y =
temp
...
x =
temp
...
y =
return temp;

min(r
...
x,
min(r
...
y,
max(r
...
x,
max(r
...
y,

r
...
x);
r
...
y);
r
...
x);
r
...
y);

}

If a large structure is to be passed to a function, it is generally more efficient to pass a pointer
than to copy the whole structure
...
The declaration
struct point *pp;

says that pp is a pointer to a structure of type struct point
...
x and (*pp)
...
To use pp, we
might write, for example,
struct point origin, *pp;
pp = &origin;
printf("origin is (%d,%d)\n", (*pp)
...
y);
The parentheses are necessary in (*pp)
...
is higher then *
...
x means *(pp
...


the structure member
which is illegal here

Pointers to structures are so frequently used that an alternative notation is provided as a
shorthand
...
So we could write instead
printf("origin is (%d,%d)\n", pp->x, pp->y);

Both
...
pt1
...
x
(r
...
x
(rp->pt1)
...
and ->, together with () for function calls and [] for subscripts, are
at the top of the precedence hierarchy and thus bind very tightly
...
Parentheses can
be used to alter binding: (++p)->len increments p before accessing len, and (p++)->len
increments p afterward
...
)
In the same way, *p->str fetches whatever str points to; *p->str++ increments str after
accessing whatever it points to (just like *s++); (*p->str)++ increments whatever str points
to; and *p++->str increments p after accessing whatever str points to
...
3 Arrays of Structures
Consider writing a program to count the occurrences of each C keyword
...
One possibility is
to use two parallel arrays, keyword and keycount, as in
char *keyword[NKEYS];
int keycount[NKEYS];

But the very fact that the arrays are parallel suggests a different organization, an array of
structures
...
The structure declaration
struct key {
char *word;
int count;
} keytab[NKEYS];

declares a structure type key, defines an array keytab of structures of this type, and sets aside
storage for them
...
This could also be written
struct key {
char *word;
int count;
};
struct key keytab[NKEYS];
Since the structure keytab contains

a constant set of names, it is easiest to make it an external
variable and initialize it once and for all when it is defined
...
*/
"unsigned", 0,
"void", 0,
"volatile", 0,
"while", 0
};

The initializers are listed in pairs corresponding to the structure members
...


but inner braces are not necessary when the initializers are simple variables or character
strings, and when all are present
...

The keyword counting program begins with the definition of keytab
...
Each word
is looked up in keytab with a version of the binary search function that we wrote in Chapter
3
...

#include ...
h>
#include ...
count++;
for (n = 0; n < NKEYS; n++)
if (keytab[n]
...
count, keytab[n]
...
tab[n-1] */
int binsearch(char *word, struct key tab[], int n)
{
int cond;
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low+high) / 2;
if ((cond = strcmp(word, tab[mid]
...

The quantity NKEYS is the number of keywords in keytab
...

s
One possibility would be to terminate the list of initializers with a null pointer, then loop
along keytab until the end is found
...
The size of the array is the size of one entry times the number of entries, so the
number of entries is just
size of keytab / size of struct key
C provides a compile-time unary operator called sizeof that can be used to compute the size
of any object
...
(Strictly, sizeof
produces an unsigned integer value whose type, size_t, is defined in the header
...
) An object can be a variable or array or structure
...

In our case, the number of keywords is the size of the array divided by the size of one
element
...

A sizeof can not be used in a #if line, because the preprocessor does not parse type names
...

Now for the function getword
...
getword fetches the next `word'
`
'from the input,
where a word is either a string of letters and digits beginning with a letter, or a single nonwhite space character
...

/* getword: get next word or character from input */
int getword(char *word, int lim)
{
int c, getch(void);
void ungetch(int);
char *w = word;
while (isspace(c = getch()))
;
if (c != EOF)
*w++ = c;
if (!isalpha(c)) {
*w = '\0';
return c;
}
for ( ; --lim > 0; w++)
if (!isalnum(*w = getch())) {
ungetch(*w);
break;
}
*w = '\0';
return word[0];
}

112
uses the getch and ungetch that we wrote in Chapter 4
...
The call to ungetch
pushes that character back on the input for the next call
...
h>
...
Our version of getword does not properly handle underscores, string constants,
comments, or preprocessor control lines
...


6
...

The external declaration of keytab need not change, but main and binsearch do need
modification
...
h>
#include ...
h>
#define MAXWORD 100
int getword(char *, int);
struct key *binsearch(char *, struct key *, int);
/* count C keywords; pointer version */
main()
{
char word[MAXWORD];
struct key *p;
while (getword(word, MAXWORD) != EOF)
if (isalpha(word[0]))
if ((p=binsearch(word, keytab, NKEYS)) != NULL)
p->count++;
for (p = keytab; p < keytab + NKEYS; p++)
if (p->count > 0)
printf("%4d %s\n", p->count, p->word);
return 0;
}
/* binsearch: find word in tab[0]
...
First, the declaration of binsearch must
indicate that it returns a pointer to struct key instead of an integer; this is declared both in

113
the function prototype and in binsearch
...

Second, the elements of keytab are now accessed by pointers
...

The initializers for low and high are now pointers to the beginning and just past the end of
the table
...
Subtraction is legal, however, so high-low is the
number of elements, and thus
mid = low + (high-low) / 2
sets mid to the element halfway between low

and high
...
The problem is that &tab[1] and &tab[n] are both outside the limits of the array tab
...
The language definition does guarantee, however, that
pointer arithmetic that involves the first element beyond the end of an array (that is, &tab[n])
will work correctly
...

Don' assume, however, that the size of a structure is the sum of the sizes of its members
...
Thus, for instance, if a char is one byte and an int four bytes, the structure
struct {
char c;
int i;
};

might well require eight bytes, not five
...

Finally, an aside on program format: when a function returns a complicated type like a
structure pointer, as in
struct key *binsearch(char *word, struct key *tab, int n)

the function name can be hard to see, and to find with a text editor
...


6
...
Since the list of words isn' known in advance, we can' conveniently
t
t
sort it and use a binary search
...
(More precisely, its running
s

114
time is likely to grow quadratically with the number of input words
...
This shouldn'be done by shifting words in a
t
linear array, though - that also takes too long
...

The tree contains one `node'per distinct word; each node contains
`
'


A pointer to the text of the word,



A count of the number of occurrences,



A pointer to the left child node,



A pointer to the right child node
...

The nodes are maintained so that at any node the left subtree contains only words that are
lexicographically less than the word at the node, and the right subtree contains only words
that are greater
...
If they match, the question is answered affirmatively
...
If there is no child in the required direction, the new word is not in the tree, and in
fact the empty slot is the proper place to add the new word
...
Accordingly, recursive
routines for insertion and printing will be most natural
...
It is illegal for a
s
structure to contain an instance of itself, but
struct tnode *left;

115
declares left to be a pointer to a tnode, not a tnode itself
...
The way to handle this is:
struct t {

...

struct t *q;
};

/* p points to an s */

/* q points to a t */

The code for the whole program is surprisingly small, given a handful of supporting routines
like getword that we have already written
...

#include ...
h>
#include ...
A word is presented by main to the top level (the root) of
the tree
...
Eventually,
the word either matches something already in the tree (in which case the count is
incremented), or a null pointer is encountered, indicating that a node must be created and
added to the tree
...

struct tnode *talloc(void);
char *strdup(char *);
/* addtree: add a node with w, at or below p */
struct treenode *addtree(struct tnode *p, char *w)
{
int cond;
if (p == NULL) {
/* a new word has arrived */
p = talloc();
/* make a new node */
p->word = strdup(w);
p->count = 1;
p->left = p->right = NULL;
} else if ((cond = strcmp(w, p->word)) == 0)
p->count++;
/* repeated word */
else if (cond < 0)
/* less than into left subtree */
p->left = addtree(p->left, w);

116
else
/* greater than into right subtree */
p->right = addtree(p->right, w);
return p;
}

Storage for the new node is fetched by a routine talloc, which returns a pointer to a free
space suitable for holding a tree node, and the new word is copied into a hidden space by
strdup
...
) The count is initialized, and the two
children are made null
...
We have (unwisely) omitted error checking on the values returned
by strdup and talloc
...
If you
feel shaky about how recursion works, simulate treeprint as it operates on the tree shown
above
...
As a worst case, if the words are
already in order, this program does an expensive simulation of linear search
...

Before leaving this example, it is also worth a brief digression on a problem related to storage
allocators
...
But if one allocator is to process requests for,
say, pointers to chars and pointers to struct tnodes, two questions arise
...

The alloc of Chapter 5 does not guarantee any particular alignment, so we will use the
standard library function malloc, which does
...

The question of the type declaration for a function like malloc is a vexing one for any
language that takes its type-checking seriously
...
malloc and related routines are declared in the standard header ...
Thus
talloc can be written as
#include ...

Storage obtained by calling malloc may be freed for re-use by calling free; see Chapters 8
and 7
...
Write a program that reads a C program and prints in alphabetical order each
group of variable names that are identical in the first 6 characters, but different somewhere
thereafter
...
Make 6 a parameter that can be
t
set from the command line
...
Write a cross-referencer that prints a list of all words in a document, and for
each word, a list of the line numbers on which it occurs
...

` '
Exercise 6-4
...
Precede each word by its count
...
6 Table Lookup
In this section we will write the innards of a table-lookup package, to illustrate more aspects
of structures
...
For example, consider the #define statement
...
Later, when the
name IN appears in a statement like
state = IN;

it must be replaced by 1
...
install(s,t)
records the name s and the replacement text t in a table; s and t are just character strings
...

t
The algorithm is a hash-search - the incoming name is converted into a small non-negative
integer, which is then used to index into an array of pointers
...
It is NULL if
no names have hashed to that value
...
A null next-pointer marks the end of the list
...
This is not the best possible hash function, but it is short and effective
...

The hashing process produces a starting index in the array hashtab; if the string is to be
found anywhere, it will be in the list of blocks beginning there
...
If lookup finds the entry already present, it returns a pointer to it; if not, it returns
NULL
...


119
uses lookup to determine whether the name being installed is already present; if so,
the new definition will supersede the old one
...
install
returns NULL if for any reason there is no room for a new entry
...
Write a function undef that will remove a name and definition from the table
maintained by lookup and install
...
Implement a simple version of the #define processor (i
...
, no arguments)
suitable for use with C programs, based on the routines of this section
...


6
...
For example, the
declaration
typedef int Length;

makes the name Length a synonym for int
...
, in exactly the same ways that the int type can be:
Length len, maxlen;
Length *lengths[];

Similarly, the declaration

typedef char *String;
makes String a synonym for char *

declarations and casts:

or character pointer, which may then be used in

String p, lineptr[MAXLINES], alloc(int);
int strcmp(String, String);
p = (String) malloc(100);
Notice that the type being declared in a typedef appears in the position of a variable name,
not right after the word typedef
...
We have used capitalized names for typedefs, to make them stand out
...
Then the routine talloc could become
Treeptr talloc(void)
{
return (Treeptr) malloc(sizeof(Treenode));
}
must be emphasized that a typedef declaration does not create

It
a new type in any sense; it
merely adds a new name for some existing type
...
In effect, typedef is like #define, except that since it is interpreted by
the compiler, it can cope with textual substitutions that are beyond the capabilities of the
preprocessor
...

Besides purely aesthetic issues, there are two main reasons for using typedefs
...
If typedefs are used for data types that
may be machine-dependent, only the typedefs need change when the program is moved
...
Types like size_t
and ptrdiff_t from the standard library are examples
...


6
...
Unions provide a way to
manipulate different kinds of data in a single area of storage, without embedding any
machine-dependent information in the program
...

As an example such as might be found in a compiler symbol table manager, suppose that a
constant may be an int, a float, or a character pointer
...
This is the purpose of a union - a single variable that can legitimately
hold any of one of several types
...
Any of these types may be assigned to u and then used in

121
expressions, so long as the usage is consistent: the type retrieved must be the type most
recently stored
...

Syntactically, members of a union are accessed as
union-name
...
If the variable utype is used to keep track of the current type stored in
u, then one might see code such as
if (utype == INT)
printf("%d\n", u
...
fval);
if (utype == STRING)
printf("%s\n", u
...
The notation for accessing a
member of a union in a structure (or vice versa) is identical to that for nested structures
...
u
...
u
...
u
...
The same operations are permitted on unions as on structures:
assignment to or copying as a unit, taking the address, and accessing a member
...

The storage allocator in Chapter 8 shows how a union can be used to force a variable to be
aligned on a particular kind of storage boundary
...
9 Bit-fields
When storage space is at a premium, it may be necessary to pack several objects into a single
machine word; one common use is a set of single-bit flags in applications like compiler

122
symbol tables
...

Imagine a fragment of a compiler that manipulates a symbol table
...
The most compact way to
encode such information is a set of one-bit flags in a single char or int
...
Then accessing the bits becomes a matter of `bit`
fiddling'
'with the shifting, masking, and complementing operators that were described in
Chapter 2
...


is true if both bits are off
...

A bit-field, or field for short, is a set of adjacent bits within a single implementation-defined
storage unit that we will call a `word
...
The number
following the colon represents the field width in bits
...

Individual fields are referenced in the same way as other structure members:
etc
...
Thus the previous examples may
be written more naturally as
flags
...
is_extern,

flags
...
is_static = 1;

to turn the bits on;

flags
...
is_static = 0;

to turn them off; and

if (flags
...
is_static == 0)

...

Almost everything about fields is implementation-dependent
...
Fields need not be names; unnamed fields (a colon
and width only) are used for padding
...

Fields are assigned left to right on some machines and right to left on others
...
Fields may be declared only as
ints; for portability, specify signed or unsigned explicitly
...


124

Chapter 7 - Input and Output
Input and output are not part of the C language itself, so we have not emphasized them in our
presentation thus far
...
In this chapter we will describe the
standard library, a set of functions that provide input and output, string handling, storage
management, mathematical routines, and a variety of other services for C programs
...
Programs that confine their system
interactions to facilities provided by the standard library can be moved from one system to
another without change
...
h>, ...
h>
...
The library is described in detail in Appendix B
...
1 Standard Input and Output
As we said in Chapter 1, the library implements a simple model of text input and output
...
If the
system doesn'operate that way, the library does whatever necessary to make it appear as if it
t
does
...

The simplest input mechanism is to read one character at a time from the standard input,
normally the keyboard, with getchar:
int getchar(void)
getchar returns the next

input character each time it is called, or EOF when it encounters end
of file
...
h>
...

In many environments, a file may be substituted for the keyboard by using the < convention
for input redirection: if a program prog uses getchar, then the command line
prog causes prog to read characters from infile instead
...
Input switching is also invisible if the

input comes from another program via a pipe mechanism: on some systems, the command
line
otherprog | prog
runs the two programs otherprog
the standard input for prog
...
putchar returns the character written, or EOF is an error occurs
...
If pipes are supported,
prog | anotherprog

puts the standard output of prog into the standard input of anotherprog
...
Calls to putchar and
printf may be interleaved - output happens in the order in which the calls are made
...
h>

before the first reference
...

Many programs read only one input stream and write only one output stream; for such
programs, input and output with getchar, putchar, and printf may be entirely adequate,
and is certainly enough to get started
...
For example, consider the program lower,
which converts its input to lower case:
#include ...
h>
main() /* lower: convert input to lower case*/
{
int c
while ((c = getchar()) != EOF)
putchar(tolower(c));
return 0;
}

The function tolower is defined in ...
As we mentioned earlier, `functions'like getchar
`
'
and putchar in ...
h> are often macros, thus avoiding the
overhead of a function call per character
...
5
...
h> functions are implemented on a given machine, programs
that use them are shielded from knowledge of the character set
...
Write a program that converts upper case to lower or lower case to upper,
depending on the name it is invoked with, as found in argv[0]
...
2 Formatted Output - printf
The output function printf translates internal values to characters
...
The description here covers most typical uses but is not
complete; for the full story, see Appendix B
...
);
printf converts, formats, and prints its arguments on the
format
...


standard output under control of the

The format string contains two types of objects: ordinary characters, which are copied to the
output stream, and conversion specifications, each of which causes conversion and printing of
the next successive argument to printf
...
Between the % and the conversion character there may be,
in order:


A minus sign, which specifies left adjustment of the converted argument
...
The converted argument will be
printed in a field at least this wide
...




A period, which separates the field width from the precision
...




An h if the integer is to be printed as a short, or l (letter ell) if as a long
...
1
...

Table 7
...
,15
...

double; [-]m
...

double; [-]m
...
ddddddE+/-xx, where the number of d'
s
is given by the precision (default 6)
...
Trailing zeros and a trailing decimal point are
not printed
...

no argument is converted; print a %

A width or precision may be specified as *, in which case the value is computed by
converting the next argument (which must be an int)
...
*s", max, s);

Most of the format conversions have been illustrated in earlier chapters
...
The following table shows the effect of a variety of
specifications in printing `hello, world'
`
'(12 characters)
...

:%s:
:%10s:
:%
...
15s:
:%-15s:
:%15
...
10s:
warning: printf

:hello, world:
:hello, world:
:hello, wor:
:hello, world:
:hello, world:
:hello, world
:
:
hello, wor:
:hello, wor
:

A
uses its first argument to decide how many arguments follow and what
their type is
...
You should also be aware of the difference between
these two calls:
printf(s);
/* FAILS if s contains % */
printf("%s", s);
/* SAFE */
The function sprintf does the same conversions as printf

string:

does, but stores the output in a

int sprintf(char *string, char *format, arg1, arg2,
...
, according to format as before, but places
the result in string instead of the standard output; string must be big enough to receive the

result
...
Write a program that will print arbitrary input in a sensible way
...


7
...
Since we are
mainly interested in the argument processing, minprintf will process the format string and
arguments but will call the real printf to do the format conversions
...
)
where the declaration
...
The
declaration
...
Our minprintf is declared as
void minprintf(char *fmt,
...

The tricky bit is how minprintf walks along the argument list when the list doesn' even
t
have a name
...
h> contains a set of macro definitions that define
how to step through an argument list
...

The type va_list is used to declare a variable that will refer to each argument in turn; in
minprintf, this variable is called ap, for `argument pointer
...
It must be called once before ap is used
...

Each call of va_arg returns one argument and steps ap to the next; va_arg uses a type name
to determine what type to return and how big a step to take
...
It must be called before the program returns
...
h>
/* minprintf: minimal printf with variable argument list */
void minprintf(char *fmt,
...
Revise minprintf to handle more of the other facilities of printf
...
4 Formatted Input - Scanf
The function scanf is the input analog of printf, providing many of the same conversion
facilities in the opposite direction
...
)
scanf reads characters from the standard input, interprets them according to the specification
in format, and stores the results through the remaining arguments
...
As with printf, this section is a summary of
the most useful features, not an exhaustive list
...
It returns as its value the number of successfully matched and assigned input
items
...
On the end of file, EOF is
returned; note that this is different from 0, which means that the next input character does not
match the first specification in the format string
...


There is also a function sscanf that reads from a string instead of the standard input:
int sscanf(char *string, char *format, arg1, arg2,
...
These arguments must be pointers
...
The format string may contain:


Blanks or tabs, which are not ignored
...


129


Conversion specifications, consisting of the character %, an optional assignment
suppression character *, an optional number specifying a maximum field width, an
optional h, l or L indicating the width of the target, and a conversion character
...
Normally the result
is places in the variable pointed to by the corresponding argument
...
An
input field is defined as a string of non-white space characters; it extends either to the next
white space character or until the field width, is specified, is exhausted
...
(White
space characters are blank, tab, newline, carriage return, vertical tab, and formfeed
...
The corresponding
argument must be a pointer, as required by the call-by-value semantics of C
...
2
...
2: Basic Scanf Conversions
Characte
r
d
i
o
u
x
c

s
e,f,g
%

Input Data; Argument type
decimal integer; int *
integer; int *
...

octal integer (with or without leading zero); int *
unsigned decimal integer; unsigned int *
hexadecimal integer (with or without leading 0x or 0X); int *
characters; char *
...
The normal skip-over white space is suppressed; to read the next
non-white space character, use %1s
character string (not quoted); char *, pointing to an array of characters long
enough for the string and a terminating '\0' that will be added
...


The conversion characters d, i, o, u, and x may be preceded by h to indicate that a pointer to
short rather than int appears in the argument list, or by l (letter ell) to indicate that a pointer
to long appears in the argument list
...
h>
main() /* rudimentary calculator */
{
double sum, v;
sum = 0;
while (scanf("%lf", &v) == 1)
printf("\t%
...


Literal characters can appear in the scanf format string; they must match the same characters
in the input
...


Furthermore, it skips over white space
(blanks, tabs, newlines, etc
...
To read input whose format is not
fixed, it is often best to read a line at a time, then pick it apart with scanf
...
Then we
could write
while (getline(line, sizeof(line)) > 0) {
if (sscanf(line, "%d %s %d", &day, monthname, &year) == 3)
printf("valid: %s\n", line); /* 25 Dec 1988 form */
else if (sscanf(line, "%d/%d/%d", &month, &day, &year) == 3)
printf("valid: %s\n", line); /* mm/dd/yy form */
else
printf("invalid: %s\n", line); /* invalid form */
}
Calls to scanf can be mixed with calls to other input functions
...


any input

A final warning: the arguments to scanf and sscanf must be pointers
...

Exercise 7-4
...

Exercise 5-5
...


7
...

The next step is to write a program that accesses a file that is not already connected to the
program
...
cat is used for printing files on the screen, and
as a general-purpose input collector for programs that do not have the capability of accessing
files by name
...
c y
...
c and y
...

The question is how to arrange for the named files to be read - that is, how to connect the
external names that a user thinks of to the statements that read the data
...
Before it can be read or written, a file has to be opened by the library
function fopen
...
c or y
...

This pointer, called the file pointer, points to a structure that contains information about the
file, such as the location of a buffer, the current character position in the buffer, whether the
file is being read or written, and whether errors or end of file have occurred
...
h> include a structure
declaration called FILE
...
Notice that
FILE is a type name, like int, not a structure tag; it is defined with a typedef
...
5
...
The second
argument is the mode, also a character string, which indicates how one intends to use the file
...
Some systems
distinguish between text and binary files; for the latter, a "b" must be appended to the mode
string
...

Opening an existing file for writing causes the old contents to be discarded, while opening for
appending preserves them
...
If
t
there is any error, fopen will return NULL
...
)
The next thing needed is a way to read or write the file once it is open
...

int getc(FILE *fp)
getc returns the next character

or error
...
Like getchar and putchar, getc and putc may be macros instead of functions
...
These files are the standard input, the standard
output, and the standard error; the corresponding file pointers are called stdin, stdout, and
stderr, and are declared in ...
Normally stdin is connected to the keyboard and
stdout and stderr are connected to the screen, but stdin and stdout may be redirected to
files or pipes as described in Section 7
...

getchar

and putchar can be defined in terms of getc, putc, stdin, and stdout as follows:

#define getchar()
#define putchar(c)

getc(stdin)
putc((c), stdout)

132
For formatted input or output of files, the functions fscanf and fprintf may be used
...

int fscanf(FILE *fp, char *format,
...
)

With these preliminaries out of the way, we are now in a position to write the program cat to
concatenate files
...
If
there are command-line arguments, they are interpreted as filenames, and processed in order
...

#include ...
They are constants, however,
not variables, so it is not possible to assign to them
...
Since most
operating systems have some limit on the number of files that a program may have open
simultaneously, it' a good idea to free the file pointers when they are no longer needed, as
s
we did in cat
...
fclose is called automatically for each open file when a
program terminates normally
...
They
can also be reassigned by the library function freopen
...
6 Error Handling - Stderr and Exit
The treatment of errors in cat is not ideal
...
That
might be acceptable if the output is going to a screen, but not if it' going into a file or into
s
another program via a pipeline
...
Output written on stderr normally
appears on the screen even if the standard output is redirected
...

#include ...
First, the diagnostic output produced by fprintf
goes to stderr, so it finds its way to the screen instead of disappearing down a pipeline or
into an output file
...

Second, the program uses the standard library function exit, which terminates program
execution when it is called
...
Conventionally, a return value of 0 signals that all is well; non-zero
values usually signal abnormal situations
...

Within main, return expr is equivalent to exit(expr)
...

The function ferror returns non-zero if an error occurred on the stream fp
...

The function feof(FILE *) is analogous to ferror; it returns non-zero if end of file has
occurred on the specified file
...


134

7
...
The resulting line is terminated with '\0'
...
(Our getline returns

the line length, which is a more useful value; zero means end of file
...

The library functions gets and puts are similar to fgets and fputs, but operate on stdin
and stdout
...

To show that there is nothing special about functions like fgets and fputs, here they are,
copied from the standard library on our system:
/* fgets: get at most n chars from iop */
char *fgets(char *s, int n, FILE *iop)
{
register int c;
register char *cs;
cs = s;
while (--n > 0 && (c = getc(iop)) != EOF)
if ((*cs++ = c) == '\n')
break;
*cs = '\0';
return (c == EOF && cs == s) ? NULL : s;
}
/* fputs: put string s on file iop */
int fputs(char *s, FILE *iop)
{
int c;
while (c = *s++)
putc(c, iop);
return ferror(iop) ? EOF : 0;
}

For no obvious reason, the standard specifies different return values for ferror and fputs
...
Write a program to compare two files, printing the first line where they differ
...
Modify the pattern finding program of Chapter 5 to take its input from a set of
named files or, if no files are named as arguments, from the standard input
...
Write a program to print a set of files, starting each new one on a new page,
with a title and a running page count for each file
...
8 Miscellaneous Functions
The standard library provides a wide variety of functions
...
More details and many other functions can be found in Appendix B
...
8
...
h>
...

s,
strcat(s,t)
concatenate t to end of s
strncat(s,t,n) concatenate n characters of t to end of s
return negative, zero, or positive for s < t, s == t, s > t
strcmp(s,t)
strncmp(s,t,n) same as strcmp but only in first n characters
strcpy(s,t)
copy t to s
strncpy(s,t,n) copy at most n characters of t to s
return length of s
strlen(s)
strchr(s,c)
return pointer to first c in s, or NULL if not present
strrchr(s,c)
return pointer to last c in s, or NULL if not present

7
...
2 Character Class Testing and Conversion
Several functions from ...
In the following,
c is an int that can be represented as an unsigned char or EOF
...

isalpha(c) non-zero if c is alphabetic, 0 if not
isupper(c) non-zero if c is upper case, 0 if not
islower(c) non-zero if c is lower case, 0 if not
isdigit(c) non-zero if c is digit, 0 if not
isalnum(c) non-zero if isalpha(c) or isdigit(c), 0 if not
isspace(c) non-zero if c is blank, tab, newline, return, formfeed, vertical tab
toupper(c) return c converted to upper case
tolower(c) return c converted to lower case

7
...
3 Ungetc
The standard library provides a rather restricted version of the function ungetch that we
wrote in Chapter 4; it is called ungetc
...
Only one
character of pushback is guaranteed per file
...


7
...
4 Command Execution
The function system(char *s) executes the command contained in the character string s,
then resumes execution of the current program
...
As a trivial example, on UNIX systems, the statement
system("date");
causes the program date to be run;
system returns a system-dependent

it prints the date and time of day on the standard output
...
In the UNIX
system, the status return is the value returned by exit
...
8
...

void *malloc(size_t n)

136
returns a pointer to n bytes of uninitialized storage, or NULL if the request cannot be satisfied
...
The storage is initialized to zero
...
There are no restrictions on the order in which space is freed, but it is a ghastly
error to free something not obtained by calling malloc or calloc
...
A typical but incorrect piece of
code is this loop that frees items from a list:
for (p = head; p != NULL; p = p->next) /* WRONG */
free(p);

The right way is to save whatever is needed before freeing:
for (p = head; p != NULL; p = q) {
q = p->next;
free(p);
}

Section 8
...


7
...
6 Mathematical Functions
There are more than twenty mathematical functions declared in ...
Each takes one or two double arguments and returns a double
...
8
...
h>
...
0))

(If your library already provides a function for floating-point random numbers, it is likely to
have better statistical properties than this one
...
The portable implementation of rand
and srand suggested by the standard appears in Section 2
...

Exercise 7-9
...

Explore both possibilities
...
This
chapter describes how to use some of the most important system calls from C programs
...
Even if you
use C on a different operating system, however, you should be able to glean insight into C
programming from studying these examples; although details vary, similar code will be found
on any system
...

This chapter is divided into three major parts: input/output, file system, and storage
allocation
...

Chapter 7 was concerned with an input/output interface that is uniform across operating
systems
...
In the next few sections we will describe
the UNIX system calls for input and output, and show how parts of the standard library can
be implemented with them
...
1 File Descriptors
In the UNIX operating system, all input and output is done by reading or writing files,
because all peripheral devices, even keyboard and screen, are files in the file system
...

In the most general case, before you read and write a file, you must inform the system of your
intent to do so, a process called opening the file
...
The system checks your right to
do so (Does the file exist? Do you have permission to access it?) and if all is well, returns to
the program a small non-negative integer called a file descriptor
...
(A
file descriptor is analogous to the file pointer used by the standard library, or to the file
handle of MS-DOS
...

Since input and output involving keyboard and screen is so common, special arrangements
exist to make this convenient
...
If a program reads 0 and writes 1 and 2, it can do input and
output without worrying about opening files
...
Normally file descriptor 2 remains attached to the screen, so error messages can
go there
...
In all cases, the
file assignments are changed by the shell, not by the program
...


138

8
...
For both, the first argument is a file descriptor
...
The third argument is the number is the number of bytes to be transferred
...
On reading, the number of bytes
returned may be less than the number requested
...
For writing, the return value is the number of
bytes written; an error has occurred if this isn'equal to the number requested
...
The most common values are 1,
which means one character at a time (`unbuffered' and a number like 1024 or 4096 that
`
'
),
corresponds to a physical block size on a peripheral device
...

Putting these facts together, we can write a simple program to copy its input to its output, the
equivalent of the file copying program written for Chapter 1
...

#include "syscalls
...
h so
we can include it in the programs of this chapter
...

The parameter BUFSIZ is also defined in syscalls
...
If the file size is not a multiple of BUFSIZ, some read will return a smaller number of
bytes to be written by write; the next call to read after that will return zero
...
For example, here is a version of getchar that does unbuffered input,
by reading the standard input one character at a time
...
h"
/* getchar: unbuffered single character input */
int getchar(void)
{
char c;
return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF;
}

must be a char, because read needs a character pointer
...


c

The second version of getchar does input in big chunks, and hands out the characters one at
a time
...
h"

139
/* getchar: simple buffered version */
int getchar(void)
{
static char buf[BUFSIZ];
static char *bufp = buf;
static int n = 0;
if (n == 0) { /* buffer is empty */
n = read(0, buf, sizeof buf);
bufp = buf;
}
return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
}

If these versions of getchar were to be compiled with ...


8
...
There are two system calls for this, open and creat [sic]
...
open returns -1 if any error occurs
...
h>
int fd;
int open(char *name, int flags, int perms);
fd = open(name, flags, perms);

As with fopen, the name argument is a character string containing the filename
...
h> on System V UNIX systems, and in ...

To open an existing file for reading,
fd = open(name, O_RDONLY,0);

The perms argument is always zero for the uses of open that we will discuss
...
The system call creat is provided to
create new files, or to re-write old ones
...
If the file already exists,
creat will truncate it to zero length, thereby discarding its previous contents; it is not an error
to creat a file that already exists
...
In the UNIX file system, there are nine bits of permission information associated
with a file that control read, write and execute access for the owner of the file, for the owner'
s
group, and for all others
...
For example, 0775 specifies read, write and execute permission for the owner,
and read and execute permission for the group and everyone else
...
Our version copies only one file, it does not permit the second argument to be a
directory, and it invents permissions instead of copying them
...
h>
#include ...
h"
#define PERMS 0666
void error(char *,

/* RW for owner, group, others */


...
With the stat system
call, described in Section 8
...

Notice that the function error is called with variable argument lists much like printf
...
The
standard library function vprintf is like printf except that the variable argument list is
replaced by a single argument that has been initialized by calling the va_start macro
...

#include ...
h>
/* error: print an error message and die */
void error(char *fmt,
...
Accordingly, any program that intends to process many files must be
prepared to re-use file descriptors
...
Termination of a program via exit or return from the main program closes all open
files
...
It
corresponds to the standard library function remove
...
Rewrite the program cat from Chapter 7 using read, write, open, and close
instead of their standard library equivalents
...


8
...
When necessary, however, a file can be read or written in any
arbitrary order
...
Subsequent reading or writing will begin at that position
...
For example, to append to a file
(the redirection >> in the UNIX shell, or "a" for fopen), seek to the end before writing:
lseek(fd, 0L, 2);

To get back to the beginning (`rewind'
`
'
),
lseek(fd, 0L, 0);

Notice the 0L argument; it could also be written as (long) 0 or just as 0 if lseek is properly
declared
...

For example, the following function reads any number of bytes from any arbitrary place in a
file
...

#include "syscalls
...
The standard library function fseek is similar to lseek except that the first argument
is a FILE * and the return is non-zero if an error occurred
...
5 Example - An implementation of Fopen and Getc
Let us illustrate how some of these pieces fit together by showing an implementation of the
standard library routines fopen and getc
...
A file pointer is a pointer to a structure that contains several pieces of
information about the file: a pointer to a buffer, so the file can be read in large chunks; a
count of the number of characters left in the buffer; a pointer to the next character position in
the buffer; the file descriptor; and flags describing read/write mode, error status, etc
...
h>, which must be included (by
#include) in any source file that uses routines from the standard input/output library
...
In the following excerpt from a typical ...
This convention is used by all
s
standard library routines
...
(Recall that a long #define is continued with a backslash
...
The characters are returned unsigned, which

ensures that all characters will be positive
...
We have also included macros for accessing the error and end-of-file status and the
file descriptor
...
Most of fopen is concerned with getting the file
opened and positioned at the right place, and setting the flag bits to indicate the proper state
...

#include ...
h"
#define PERMS 0666
/* RW for owner, group, others */

143
FILE *fopen(char *name, char *mode)
{
int fd;
FILE *fp;
if (*mode != 'r' && *mode != 'w' && *mode != 'a')
return NULL;
for (fp = _iob; fp < _iob + OPEN_MAX; fp++)
if ((fp->flag & (_READ | _WRITE)) == 0)
break;
/* found free slot */
if (fp >= _iob + OPEN_MAX)
/* no free slots */
return NULL;
if (*mode == 'w')
fd = creat(name, PERMS);
else if (*mode == 'a') {
if ((fd = open(name, O_WRONLY, 0)) == -1)
fd = creat(name, PERMS);
lseek(fd, 0L, 2);
} else
fd = open(name, O_RDONLY, 0);
if (fd == -1)
/* couldn't access name */
return NULL;
fp->fd = fd;
fp->cnt = 0;
fp->base = NULL;
fp->flag = (*mode == 'r') ? _READ : _WRITE;
return fp;
}

This version of fopen does not handle all of the access mode possibilities of the standard,
though adding them would not take much code
...

The first call to getc for a particular file finds a count of zero, which forces a call of
_fillbuf
...

Otherwise, it tries to allocate a buffer (if reading is to be buffered)
...
Subsequent calls to _fillbuf will find a
buffer allocated
...
h"
/* _fillbuf: allocate and fill input buffer */
int _fillbuf(FILE *fp)
{
int bufsize;
if ((fp->flag&(_READ|_EOF_ERR)) != _READ)
return EOF;
bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZ;
if (fp->base == NULL)
/* no buffer yet */
if ((fp->base = (char *) malloc(bufsize)) == NULL)
return EOF;
/* can't get buffer */
fp->ptr = fp->base;
fp->cnt = read(fp->fd, fp->ptr, bufsize);
if (--fp->cnt < 0) {
if (fp->cnt == -1)
fp->flag |= _EOF;
else
fp->flag |= _ERR;
fp->cnt = 0;
return EOF;
}

144
return (unsigned char) *fp->ptr++;
}

The only remaining loose end is how everything gets started
...


be read, stdout is to

Exercise 8-2
...

Compare code size and execution speed
...
Design and write _flushbuf, fflush, and fclose
...
The standard library function
int fseek(FILE *fp, long offset, int origin)
is identical to lseek except that fp is a file pointer instead of a file descriptor and return
value is an int status, not a position
...
Make sure that your fseek coordinates

properly with the buffering done for the other functions of the library
...
6 Example - Listing Directories
A different kind of file system interaction is sometimes called for - determining information
about a file, not what it contains
...
The MS-DOS dir command is analogous
...
But is is
necessary to use a system call to access other information about a file, such as its size
...
What we want is provide access to the information in a relatively systemindependent way, even though the implementation may be highly system-dependent
...
fsize is a special form of
ls that prints the sizes of all files named in its commandline argument list
...
If there are no arguments at
all, it processes the current directory
...
A directory is a file that
contains a list of filenames and some indication of where they are located
...
'
`
'The inode for a file is where all
information about the file except its name is kept
...

Regrettably, the format and precise contents of a directory are not the same on all versions of
the system
...

The outer level defines a structure called a Dirent and three routines opendir, readdir, and
closedir to provide system-independent access to the name and inode number in a directory
entry
...
Then we will show how to implement these on
systems that use the same directory structure as Version 7 and System V UNIX; variants are
left as exercises
...
The maximum length of a
filename component is NAME_MAX, which is a system-dependent value
...

This information is collected into a file called dirent
...

#define NAME_MAX

14

/* longest filename component; */
/* system-dependent */

typedef struct {
/* portable directory entry */
long ino;
/* inode number */
char name[NAME_MAX+1];
/* name + '\0' terminator */
} Dirent;
typedef struct {
int fd;
Dirent d;
} DIR;

/* minimal DIR: no buffering, etc
...
That is,

and returns all of the information in the inode for that

char *name;
struct stat stbuf;
int stat(char *, struct stat *);
stat(name, &stbuf);
fills the structure stbuf with the inode information for the file name
...
h>, and typically looks like this:
struct stat
{
dev_t
ino_t
short
short
short
short
dev_t
off_t
time_t
time_t
time_t
};

describing

/* inode information returned by stat */
st_dev;
st_ino;
st_mode;
st_nlink;
st_uid;
st_gid;
st_rdev;
st_size;
st_atime;
st_mtime;
st_ctime;

/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*

device of inode */
inode number */
mode bits */
number of links to file */
owners user id */
owners group id */
for special files */
file size in characters */
time last accessed */
time last modified */
time originally created */

Most of these values are explained by the comment fields
...
h>, which must be included too
...
The flag definitions are also
included in ...
*/

0160000
0040000
0020000
0060000
0010000

/*
/*
/*
/*
/*

type of file: */
directory */
character special */
block special */
regular */

Now we are ready to write the program fsize
...
If the name is a
directory, however, then we have to process that directory one file at a time; it may in turn
contain sub-directories, so the process is recursive
...


146
#include
#include
#include
#include
#include
#include
#include

...
h>
"syscalls
...
h>
...
h>
"dirent
...
");
else
while (--argc > 0)
fsize(*++argv);
return 0;
}
The function fsize prints the size of the file
...
Note how the flag names S_IFMT and S_IFDIR are
used to decide if the file is a directory
...

int stat(char *, struct stat *);
void dirwalk(char *, void (*fcn)(char *));
/* fsize: print the name of file "name" */
void fsize(char *name)
{
struct stat stbuf;
if (stat(name, &stbuf) == -1) {
fprintf(stderr, "fsize: can't access %s\n", name);
return;
}
if ((stbuf
...
st_size, name);
}

The function dirwalk is a general routine that applies a function to each file in a directory
...
Since fsize calls dirwalk on each directory, the two functions call
each other recursively
...
") == 0
|| strcmp(dp->name, "
...
Each directory always contains entries for itself, called "
...
";
these must be skipped, or the program will loop forever
...
The next
step is to present minimal versions of opendir, readdir, and closedir for a specific system
...
h>, which looks like this:
#ifndef DIRSIZ
#define DIRSIZ 14
#endif
struct direct {
/* directory entry */
ino_t d_ino;
/* inode number */
char d_name[DIRSIZ]; /* long name does not have '\0' */
};

Some versions of the system permit much longer names and have a more complicated
directory structure
...
It happens to be
unsigned short on the systems we use regularly, but this is not the sort of information to
embed in a program; it might be different on a different system, so the typedef is better
...
h>
...
st_mode & S_IFMT) != S_IFDIR
|| (dp = (DIR *) malloc(sizeof(DIR))) == NULL)
return NULL;
dp->fd = fd;
return dp;
}
closedir

closes the directory file and frees the space:

/* closedir: close directory opened by opendir */
void closedir(DIR *dp)
{
if (dp) {
close(dp->fd);
free(dp);
}

148
}

Finally, readdir uses read to read each directory entry
...

Otherwise, the inode number and name are placed in a static structure and a pointer to that
is returned to the user
...

#include ...
d_ino == 0) /* slot not in use */
continue;
d
...
d_ino;
strncpy(d
...
d_name, DIRSIZ);
d
...
First, many programs are not `system programs' they merely use information that is
`
'
;
maintained by the operating system
...
The second observation is that with care
it is possible to create an interface to system-dependent objects that is itself relatively systemindependent
...

Exercise 8-5
...


8
...
The version that
we will now write is unrestricted
...
These routines illustrate
some of the considerations involved in writing machine-dependent code in a relatively
machine-independent way, and also show a real-life application of structures, unions and
typedef
...
Since other activities in the program may also request space
without calling this allocator, the space that malloc manages may not be contiguous
...
Each block contains a size, a pointer to the next
block, and the space itself
...


149

When a request is made, the free list is scanned until a big-enough block is found
...
If the block is exactly the size requested it is unlinked from the
list and returned to the user
...
If no big-enough block is
found, another large chunk is obtained by the operating system and linked into the free list
...
If the block being freed is adjacent to a free block on either side, it is coalesced with it
into a single bigger block, so storage does not become too fragmented
...

One problem, which we alluded to in Chapter 5, is to ensure that the storage returned by
malloc is aligned properly for the objects that will be stored in it
...
On some machines, the most restrictive type is
a double; on others, int or long suffices
...
'
`
'
To simplify alignment, all blocks are multiples of the header size, and the header is aligned
properly
...

In malloc, the requested size in characters is rounded up to the proper number of headersized units; the block that will be allocated contains one more unit, for the header itself, and
this is the value recorded in the size field of the header
...
The user can do anything with the space
requested, but if anything is written outside of the allocated space the list is likely to be
scrambled
...

The variable base is used to get started
...
In
any case, the free list is then searched
...
If a too-big block is found, the tail end is returned to the user; in this way the
header of the original needs only to have its size adjusted
...

static Header base;
/* empty list to get started */
static Header *freep = NULL;
/* start of free list */
/* malloc: general-purpose storage allocator */
void *malloc(unsigned nbytes)
{
Header *p, *prevp;
Header *moreroce(unsigned);
unsigned nunits;
nunits = (nbytes+sizeof(Header)-1)/sizeof(header) + 1;
if ((prevp = freep) == NULL) {
/* no free list yet */
base
...
ptr = freeptr = prevptr = &base;
base
...
size = 0;
}
for (p = prevp->s
...
ptr) {
if (p->s
...
size == nunits) /* exactly */
prevp->s
...
ptr;
else {
/* allocate tail end */
p->s
...
size;
p->s
...
The details of how it does
this vary from system to system
...
we don'want to do that on every call to malloc, so morecore requests
t
al least NALLOC units; this larger block will be chopped up as needed
...


151
The UNIX system call sbrk(n) returns a pointer to n more bytes of storage
...
The -1 must be cast
to char * so it can be compared with the return value
...
There is still
one assumption, however, that pointers to different blocks returned by sbrk can be
meaningfully compared
...
Thus this version of malloc is portable only among
machines for which general pointer comparison is meaningful
...
size = nu;
free((void *)(up+1));
return freep;
}
free

itself is the last thing
...
This is either between two existing blocks or at the end of the list
...

The only troubles are keeping the pointers pointing to the right things and the sizes correct
...
ptr); p = p->s
...
ptr && (bp > p || bp < p->s
...
ptr) {
/* join to upper nbr */
bp->s
...
ptr->s
...
ptr = p->s
...
ptr;
} else
bp->s
...
ptr;
if (p + p->size == bp) {
/* join to lower nbr */
p->s
...
size;
p->s
...
ptr;
} else
p->s
...
The use of typedef and union handles alignment (given that sbrk supplies an
appropriate pointer)
...
Even though the details here are related to storage
allocation, the general approach is applicable to other situations as well
...
The standard library function calloc(n,size) returns a pointer to n objects of
size size, with the storage initialized to zero
...

Exercise 8-7
...
Improve these routines so they
make more pains with error checking
...
Write a routine bfree(p,n) that will free any arbitrary block p of n characters
into the free list maintained by malloc and free
...


153

Appendix A - Reference Manual
A
...
159-1989
...

For the most part, this document follows the broad outline of the standard, which in turn
follows that of the first edition of this book, although the organization differs in detail
...

Throughout this manual, commentary material is indented and written in smaller type, as this is
...


A
...
It is translated in several
phases, which are described in Par
...
12
...
When the preprocessing of Par
...
12 is
complete, the program has been reduced to a sequence of tokens
...
2
...
Blanks, horizontal and vertical tabs, newlines, formfeeds and comments as
described below (collectively, `white space' are ignored except as they separate tokens
...

If the input stream has been separated into tokens up to a given character, the next token is
the longest string of characters that could constitute a token
...
2
...
Comments
do not nest, and they do not occur within a string or character literals
...
2
...
The first character must be a letter; the
underscore _ counts as a letter
...
Identifiers may
have any length, and for internal identifiers, at least the first 31 characters are significant;
some implementations may take more characters significant
...
A
...
2)
...


A
...
4 Keywords
The following identifiers are reserved for the use as keywords, and may not be used
otherwise:
auto
break

double
else

int
long

struct
switch

154

Some

case
char
const
continue
default
do

enum
extern
float
for
goto
if

register
typedef
return
union
short
unsigned
signed
void
sizeof
volatile
static
while
implementations also reserve the words fortran and asm
...


A
...
5 Constants
There are several kinds of constants
...
A
...
2 discusses the basic
types:
constant:
integer-constant
character-constant
floating-constant
enumeration-constant
A
...
5
...
Octal constants do not contain the digits 8 or 9
...
The hexadecimal
digits include a or A through f or F with values 10 through 15
...
It may
also be suffixed by the letter l or L to specify that it is long
...
(See Par
...
4 for a
discussion of types)
...
If it is unsuffixed, octal or
hexadecimal, it has the first possible of these types: int, unsigned int, long int,
unsigned long int
...
If
it is suffixed by l or L, then long int, unsigned long int
...

The elaboration of the types of integer constants goes considerably beyond the first edition, which
merely caused large integer constants to be long
...


A
...
5
...
The value of a character constant with only one character is the numeric value of the
character in the machine' character set at execution time
...

Character constants do not contain the ' character or newlines; in order to represent them,
and certain other characters, the following escape sequences may be used:
newline
horizontal tab
vertical tab
backspace
carriage return
formfeed
audible alert

NL (LF)
HT
VT
BS
CR
FF
BEL

\n
\t
\v
\b
\r
\f
\a

backslash
question mark
single quote
double quote
octal number
hex number

\

\\

?

\?

'

\'

\"
"
ooo \ooo
hh

\xhh

155
The escape \ooo consists of the backslash followed by 1, 2, or 3 octal digits, which are taken
to specify the value of the desired character
...
The escape \xhh consists of the
backslash, followed by x, followed by hexadecimal digits, which are taken to specify the
value of the desired character
...
For either octal
or hexadecimal escape characters, if the implementation treats the char type as signed, the
value is sign-extended as if cast to char type
...

In some implementations, there is an extended set of characters that cannot be represented in
the char type
...
Such a constant has type wchar_t, an integral type
defined in the standard header ...
As with ordinary character constants,
hexadecimal escapes may be used; the effect is undefined if the specified value exceeds that
representable with wchar_t
...

Extended characters are also new
...


A
...
5
...
The
integer and fraction parts both consist of a sequence of digits
...
The type is determined by the suffix; F or f makes it float, L or l
makes it long double, otherwise it is double
...
5
...
A
...
4) are constants of type int
...
2
...
A string has type `array of characters'
`
'and storage class static (see
Par
...
3 below) and is initialized with the given characters
...

Adjacent string literals are concatenated into a single string
...
String
literals do not contain newline or double-quote characters; in order to represent them, the
same escape sequences as for character constants are available
...
Wide-character string literals have type `array of wchar_t
...

The specification that string literals need not be distinct, and the prohibition against modifying them,
are new in the ANSI standard, as is the concatenation of adjacent string literals
...


A
...
Alternative categories are usually listed
on separate lines; in a few cases, a long set of narrow alternatives is presented on one line,

156
marked by the phrase `one of
...
The syntax is summarized in Par
...
13
...


A
...
An object, sometimes called a variable, is a location in storage, and its interpretation
depends on two main attributes: its storage class and its type
...
A name also has a scope, which is the
region of the program in which it is known, and a linkage, which determines whether the
same name in another scope refers to the same object or function
...
A
...


A
...
1 Storage Class
There are two storage classes: automatic and static
...
Automatic objects are local to a
s
block (Par
...
3), and are discarded on exit from the block
...
Objects declared register are automatic, and are (if possible) stored in fast registers of
the machine
...
Within a block, including a block
that provides the code for a function, static objects are declared with the keyword static
...
They may be made local to a particular translation unit by use of the static keyword;
this gives them internal linkage
...


A
...
2 Basic Types
There are several fundamental types
...
h> described in Appendix
B defines the largest and smallest values of each type in the local implementation
...

Objects declared as characters (char) are large enough to store any member of the execution
character set
...
Other quantities may be
stored into char variables, but the available range of values, and especially whether the value
is signed, is implementation-dependent
...

unsigned char type does not appear in the first edition of this book, but is in common use
...


Besides the char types, up to three sizes of integer, declared short int, int, and long int,
are available
...
Longer integers provide at
least as much storage as shorter ones, but the implementation may make plain integers

157
equivalent to either short integers, or long integers
...

Unsigned integers, declared using the keyword unsigned, obey the laws of arithmetic
modulo 2n where n is the number of bits in the representation, and thus arithmetic on
unsigned quantities can never overflow
...

Any of single precision floating point (float), double precision floating point (double), and
extra precision floating point (long double) may be synonymous, but the ones later in the
list are at least as precise as those before
...
The first edition made long float equivalent to double; the locution has
been withdrawn
...
A
...
4)
...

Because objects of these types can be interpreted as numbers, they will be referred to as
arithmetic types
...
The types float, double, and
long double will be called floating types
...
It is used as the type returned by functions
that generate no value
...
4
...

In general these methods of constructing objects can be applied recursively
...
4
...
Declaring an object const announces that its
s
value will not be changed; declaring it volatile announces that it has special properties
relevant to optimization
...
Qualifiers are discussed in Par
...
8
...


A
...
An
obvious example of an lvalue expression is an identifier with suitable type and storage class
...
The name `lvalue'comes from
the assignment expression E1 = E2 in which the left operand E1 must be an lvalue
expression
...


A
...
This section explains the result to be expected from such
conversions
...
6
...


A
...
1 Integral Promotion
A character, a short integer, or an integer bit-field, all either signed or not, or an object of
enumeration type, may be used in an expression wherever an integer may be used
...
This process is called integral promotion
...
6
...
In a two' complement representation, this is equivalent to
s
left-truncation if the bit pattern of the unsigned type is narrower, and to zero-filling unsigned
values and sign-extending signed values if the unsigned type is wider
...


A
...
3 Integer and Floating
When a value of floating type is converted to integral type, the fractional part is discarded; if
the resulting value cannot be represented in the integral type, the behavior is undefined
...

When a value of integral type is converted to floating, and the value is in the representable
range but is not exactly representable, then the result may be either the next higher or next
lower representable value
...


A
...
4 Floating Types
When a less precise floating value is converted to an equally or more precise floating type,
the value is unchanged
...
If the result is out of range, the behavior is
undefined
...
6
...
The effect is to
bring operands into a common type, which is also the type of the result
...



First, if either operand is long double, the other is converted to long double
...




Otherwise, if either operand is float, the other is converted to float
...




Otherwise, if one operand is long int and the other is unsigned int, the effect
depends on whether a long int can represent all values of an unsigned int; if so,
the unsigned int operand is converted to long int; if not, both are converted to
unsigned long int
...




Otherwise, if either operand is unsigned int, the other is converted to unsigned
int
...

There are two changes here
...
Second,
shorter unsigned types, when combined with a larger signed type, do not propagate the unsigned
property to the result type; in the first edition, the unsigned always dominated
...
Unexpected results may still occur when an unsigned expression is compared to
a signed expression of the same size
...
6
...
A
...
7)
...
A
...
7)
...
This
produces a null pointer that is equal to another null pointer of the same type, but unequal to
any pointer to a function or object
...
They must be specified by an explicit type-conversion operator, or cast (Pars
...
7
...
8
...

A pointer may be converted to an integral type large enough to hold it; the required size is
implementation-dependent
...

A pointer to one type may be converted to a pointer to another type
...
It is guaranteed that a pointer to an object may be converted to a pointer to
an object whose type requires less or equally strict storage alignment and back again without
change; the notion of `alignment'is implementation-dependent, but objects of the char types
`
'
have least strict alignment requirements
...
A
...
8, a pointer may also be
converted to type void * and back again without change
...
A
...
4, A
...
2) of the object type to which the pointer refers
...
If qualifiers are removed, operations on the underlying object remain
subject to the qualifiers in its actual declaration
...
Calling
the function specified by the converted pointer is implementation-dependent; however, if the
converted pointer is reconverted to its original type, the result is identical to the original
pointer
...
6
...
Because a void expression denotes
a nonexistent value, such an expression may be used only where the value is not required, for

160
example as an expression statement (Par
...
9
...
A
...
18)
...
For example, a void cast documents
the discarding of the value of a function call used as an expression statement
...


A
...
8 Pointers to Void
Any pointer to an object may be converted to type void * without loss of information
...
Unlike
the pointer-to-pointer conversions discussed in Par
...
6
...

This interpretation of void * pointers is new; previously, char * pointers played the role of generic
pointer
...


A
...
Thus, for example, the expressions referred to as the
operands of + (Par
...
7
...
A
...
1-A
...
6
...
Left- or right-associativity is specified in
each subsection for the operators discussed therein
...
13
incorporates the precedence and associativity of the operators
...
That is, unless the definition of the operator guarantees that its operands are evaluated
in a particular order, the implementation is free to evaluate operands in any order, or even to
interleave their evaluation
...

This rule revokes the previous freedom to reorder expressions with operators that are mathematically
commutative and associative, but can fail to be computationally associative
...


The handling of overflow, divide check, and other exceptions in expression evaluation is not
defined by the language
...

Treatment of division by 0, and all floating-point exceptions, varies among implementations;
sometimes it is adjustable by a non-standard library function
...
7
...
'
`
'This conversion does not take place if the expression is in the
operand of the unary & operator, or of ++, --, sizeof, or as the left operand of an assignment
operator or the
...
Similarly, an expression of type `function returning T,'
`
'except
when used as the operand of the & operator, is converted to `pointer to function returning T
...
7
...

primary-expression
identifier
constant
string
(expression)

161
An identifier is a primary expression, provided it has been suitably declared as discussed
below
...
An identifier is an lvalue if it refers to an object
(Par
...
5) and if its type is arithmetic, structure, union, or pointer
...
Its type depends on its form as discussed in Par
...
2
...

A string literal is a primary expression
...
A
...
1, this is usually
`
'
),
'
modified to `pointer to char'(wchar_t) and the result is a pointer to the first character in the
`
string
...
A
...
7
...
The precedence of parentheses does not affect whether the
expression is an lvalue
...
7
...

postfix-expression:
primary-expression
postfix-expression[expression]
postfix-expression(argument-expression-listopt)
postfix-expression
...
7
...
1 Array References
A postfix expression followed by an expression in square brackets is a postfix expression
denoting a subscripted array reference
...
The expression E1[E2] is identical (by definition) to *((E1)+(E2))
...
A
...
6
...

A
...
3
...
A7
...
If the postfix expression consists
of an identifier for which no declaration exists in the current scope, the identifier is implicitly
declared as if the declaration
extern int

identifier();

had been given in the innermost block containing the function call
...
A7
...

'
In the first edition, the type was restricted to `function,'and an explicit * operator was required to call
`
'
through pointers to functions
...
The older
syntax is still usable
...
The terms `actual argument (parameter)'
`
'and `formal argument
`
(parameter)'respectively are sometimes used for the same distinction
...
A function may change the values of its parameter objects, which are
copies of the argument expressions, but these changes cannot affect the values of the
arguments
...

There are two styles in which functions may be declared
...
In the old style, parameter types are not specified
...
A
...
6
...
10
...

If the function declaration in scope for a call is old-style, then default argument promotion is
applied to each argument as follows: integral promotion (Par
...
6
...
The effect of the
call is undefined if the number of arguments disagrees with the number of parameters in the
definition of the function, or if the type of an argument after promotion disagrees with that of
the corresponding parameter
...
If it is old-style, then the comparison is between the promoted type of
the arguments of the call, and the promoted type of the parameter, if the definition is newstyle, the promoted type of the argument must be that of the parameter itself, without
promotion
...

s
The number of arguments must be the same as the number of explicitly described parameters,
unless the declaration' parameter list ends with the ellipsis notation (,
...
If the definition of the function is old-style, then the type of each
parameter in the definition, after the definition parameter' type has undergone argument
s
promotion
...
Mixtures are to be avoided if possible
...

However, the arguments and the function designator are completely evaluated, including all
side effects, before the function is entered
...

A
...
3
...
The
first operand expression must be a structure or a union, and the identifier must name a
member of the structure or union
...
The expression is an lvalue if the first expression is an
lvalue, and if the type of the second expression is not an array type
...
The first operand expression must be a pointer to a structure or union, and
the identifier must name a member of the structure or union
...

Thus the expression E1->MOS is the same as (*E1)
...
Structures and unions are discussed
in Par
...
8
...


163
In the first edition of this book, it was already the rule that a member name in such an expression had to
belong to the structure or union mentioned in the postfix expression; however, a note admitted that this
rule was not firmly enforced
...


A
...
3
...
The value of the
expression is the value of the operand
...
The operand must be an lvalue; see the discussion of additive
operators (Par
...
7
...
A
...
17) for further constraints on the operand and
details of the operation
...


A
...
4 Unary Operators
Expressions with unary operators group right-to-left
...
7
...
1 Prefix Incrementation Operators
A unary expression followed by a ++ or -- operator is a unary expression
...
The value of the expression is the value after the
incrementation (decrementation)
...
A
...
7) and assignment (Par
...
7
...
The result is not an lvalue
...
7
...
2 Address Operator
The unary operator & takes the address of its operand
...
The result is a pointer to the object or function referred to by the lvalue
...
'
`
'
A
...
4
...
It is an lvalue if the operand is a pointer to an object of arithmetic, structure,
union, or pointer type
...

A
...
4
...
An integral operand undergoes integral promotion
...

The unary + is new with the ANSI standard
...


A
...
4
...
An integral operand undergoes integral promotion
...
The type of the result is the type
of the promoted operand
...
7
...
6 One's Complement Operator
The operand of the ~ operator must have integral type, and the result is the one' complement
s
of its operand
...
If the operand is unsigned, the result is
computed by subtracting the value from the largest value of the promoted type
...
The type of the result is
the type of the promoted operand
...
7
...
7 Logical Negation Operator
The operand of the ! operator must have arithmetic type or be a pointer, and the result is 1 if
the value of its operand compares equal to 0, and 0 otherwise
...

A
...
4
...
The operand is either an expression, which is not evaluated, or a parenthesized type
name
...
When applied to a structure or union, the result is the
number of bytes in the object, including any padding required to make the object tile an array:
the size of an array of n elements is n times the size of one element
...
The result is an
unsigned integral constant; the particular type is implementation-defined
...
h> (See appendix B) defines this type as size_t
...
7
...

cast-expression:
unary expression
(type-name) cast-expression
This construction is called a cast
...
A
...
8
...
A
...
An expression with a cast is not an lvalue
...
7
...

multiplicative-expression:
multiplicative-expression * cast-expression
multiplicative-expression / cast-expression
multiplicative-expression % cast-expression
The operands of * and / must have arithmetic type; the operands of % must have integral type
...

The binary * operator denotes multiplication
...
Otherwise,
it is always true that (a/b)*b + a%b is equal to a
...


A
...
7 Additive Operators

165
The additive operators + and - group left-to-right
...
There are some additional type possibilities for
each operator
...
A pointer to an object in an array and
a value of any integral type may be added
...
The sum is a pointer of the
same type as the original pointer, and points to another object in the same array, appropriately
offset from the original object
...
If the sum pointer points outside the bounds of
the array, except at the first location beyond the high end, the result is undefined
...
It legitimizes a common idiom for
looping over the elements of an array
...
A value of any integral type
may be subtracted from a pointer, and then the same conversions and conditions as for
addition apply
...
The type of the result is defined as ptrdiff_t in the standard header
...
The value is undefined unless the pointers point to objects within the same
array; however, if P points to the last member of an array, then (P+1)-P has value 1
...
7
...
For both operators, each operand must be
integral, and is subject to integral the promotions
...
The result is undefined if the right operand is negative, or greater than
or equal to the number of bits in the left expression' type
...
The value of E1>>E2 is E1 right-shifted
E2 bit positions
...


A
...
9 Relational Operators
The relational operators group left-to-right, but this fact is not useful; a(a ...
The type of the result is int
...
Pointers to objects of the same type
(ignoring any qualifiers) may be compared; the result depends on the relative locations in the
address space of the pointed-to objects
...
If P points to the last member
of an array, then P+1 compares higher than P, even though P+1 points outside the array
...

These rules slightly liberalize the restrictions stated in the first edition, by permitting comparison of
pointers to different members of a structure or union
...


A
...
10 Equality Operators
equality-expression:
relational-expression
equality-expression == relational-expression
equality-expression != relational-expression
The == (equal to) and the != (not equal to) operators are analogous to the relational operators
except for their lower precedence
...
)
The equality operators follow the same rules as the relational operators, but permit additional
possibilities: a pointer may be compared to a constant integral expression with value 0, or to a
pointer to void
...
A
...
6
...
7
...
The operator applies only to integral operands
...
7
...
The operator applies only to integral operands
...
7
...
The operator applies only to integral operands
...
7
...
It returns 1 if both its operands compare unequal to zero,
0 otherwise
...
Otherwise, the
right operand is evaluated, and if it is equal to 0, the expression' value is 0, otherwise 1
...
The result is int
...
7
...
It returns 1 if either of its operands compare unequal to
zero, and 0 otherwise
...

Otherwise, the right operand is evaluated, and if it is unequal to 0, the expression' value is 1,
s
otherwise 0
...
The result is int
...
7
...
Only one
of the second and third operands is evaluated
...
If both are void, or structures or unions of the same type, or pointers
to objects of the same type, the result has the common type
...
If one is a
pointer to void and the other is another pointer, the other pointer is converted to a pointer to
void, and that is the type of the result
...
A
...
2) in the type to which the
pointer points are insignificant, but the result type inherits qualifiers from both arms of the
conditional
...
7
...

assignment-expression:
conditional-expression
unary-expression assignment-operator assignment-expression
assignment-operator: one of
= *= /= %= += -= <<= >>= &= ^= |=

All require an lvalue as left operand, and the lvalue must be modifiable: it must not be an
array, and must not have an incomplete type, or be a function
...
The type of an assignment expression is that of its left
operand, and the value is the value stored in the left operand after the assignment has taken
place
...
One of the following must be true: both operands have arithmetic
type, in which case the right operand is converted to the type of the left by the assignment; or
both operands are structures or unions of the same type; or one operand is a pointer and the
other is a pointer to void, or the left operand is a pointer and the right operand is a constant
expression with value 0; or both operands are pointers to functions or objects whose types are
the same except for the possible absence of const or volatile in the right operand
...


A
...
18 Comma Operator
expression:
assignment-expression
expression , assignment-expression
A pair of expressions separated by a comma is evaluated left-to-right, and the value of the left
expression is discarded
...
All side effects from the evaluation of the left-operand are completed before
beginning the evaluation of the right operand
...
A
...
3
...
A
...
7), the required syntactic unit is an assignment expression, so the comma operator
appears only in a parenthetical grouping, for example,
f(a, (t=3, t+2), c)

has three arguments, the second of which has the value 5
...
7
...

Constant expressions may not contain assignments, increment or decrement operators,
function calls, or comma operators; except in an operand of sizeof
...
This necessarily rules out arrays, indirection, address-of,
and structure member operations
...
)
More latitude is permitted for the constant expressions of initializers; the operands may be
any type of constant, and the unary & operator may be applied to external or static objects,
and to external and static arrays subscripted with a constant expression
...

Initializers must evaluate either to a constant or to the address of a previously declared
external or static object plus or minus a constant
...
See Par
...
12
...


A
...
Declarations that reserve storage are called
definitions
...

declaration-specifiers:
storage-class-specifier declaration-specifiersopt
type-specifier declaration-specifiersopt
type-qualifier declaration-specifiersopt
init-declarator-list:
init-declarator
init-declarator-list , init-declarator
init-declarator:
declarator
declarator = initializer
Declarators will be discussed later (Par
...
8
...
A
declaration must have at least one declarator, or its type specifier must declare a structure tag,
a union tag, or the members of an enumeration; empty declarations are not permitted
...
8
...
A
...
4
...
Such declarations also serve as definitions and cause storage to
be reserved
...
Only a few objects are actually placed into
registers, and only certain types are eligible; the restrictions are implementation-dependent
...

The rule that it is illegal to calculate the address of an object declared register, but actually taken to
be auto, is new
...
Inside a function, this specifier causes storage to be allocated, and
serves as a definition; for its effect outside a function, see Par
...
11
...


170
A declaration with extern, used inside a function, specifies that the storage for the declared
objects is defined elsewhere; for its effects outside a function, see Par
...
11
...

The typedef specifier does not reserve storage and is called a storage class specifier only for
syntactic convenience; it is discussed in Par
...
8
...

At most one storage class specifier may be given in a declaration
...
See Pars
...
10-A
...


A
...
2 Type Specifiers
The type-specifiers are
type specifier:
void
char
short
int
long
float
double
signed
unsigned

struct-or-union-specifier
enum-specifier
typedef-name
At most one of the words long or short may be specified together with int; the meaning is
the same if int is not mentioned
...
At
most one of signed or unsigned may be specified together with int or any of its short or
long varieties, or with char
...
The
signed specifier is useful for forcing char objects to carry a sign; it is permissible but
redundant with other integral types
...
If the type-specifier is
missing from a declaration, it is taken to be int
...

type-qualifier:
const
volatile

Type qualifiers may appear with any type specifier
...
There are no implementation-dependent semantics for volatile
objects
...
The purpose of const is to
announce objects that may be placed in read-only memory, and perhaps to increase opportunities for
optimization
...
For example, for a machine with memory-mapped input/output, a pointer to a
device register might be declared as a pointer to volatile, in order to prevent the compiler from
removing apparently redundant references through the pointer
...


A
...
3 Structure and Union Declarations

171
A structure is an object consisting of a sequence of named members of various types
...

Structure and union specifiers have the same form
...
A
structure member may also consist of a specified number of bits
...

struct-declarator:
declarator
declaratoropt : constant-expression
A type specifier of the form
struct-or-union identifier { struct-declaration-list }
declares the identifier to be the tag of the structure or union specified by the list
...
Objects with an incomplete structure or union type may be mentioned in
contexts where their size is not needed, for example in declarations (not definitions), for
specifying a pointer, or for creating a typedef, but not otherwise
...
Even in specifiers with a list, the structure or union type being declared is incomplete
within the list, and becomes complete only at the } terminating the specifier
...
Therefore, it is impossible to
declare a structure or union containing an instance of itself
...

A very special rule applies to declarations of the form
struct-or-union identifier;
that declare a structure or union, but have no declaration list and no declarators
...
A
...
1), this
declaration makes the identifier the tag of a new, incompletely-typed structure or union in the
current scope
...
It is intended to deal with mutually-recursive structures declared in an
inner scope, but whose tags might already be declared in the outer scope
...

The names of members and tags do not conflict with each other or with ordinary variables
...

In the first edition of this book, the names of structure and union members were not associated with
their parent
...


A non-field member of a structure or union may have any object type
...
Adjacent field
members of structures are packed into implementation-dependent storage units in an
implementation-dependent direction
...
An
unnamed field with width 0 forces this padding, so that the next field will begin at the edge of
the next allocation unit
...
It is
advisable to read the language rules for storing bit-fields as `implementation-dependent'
`
'without
qualification
...
In the second case, it is necessary to understand the rules of the local implementation
...
A
non-field member of a structure is aligned at an addressing boundary depending on its type;
therefore, there may be unnamed holes in a structure
...

A union may be thought of as a structure all of whose members begin at offset 0 and whose
size is sufficient to contain any of its members
...
If a pointr to a union is cast to the type of a pointer to a member, the
result refers to that member
...

Once this declaration has bene given, the declaration

173
struct tnode s, *sp;
declares s to be a structure of

the given sort, and sp to be a pointer to a structure of the given
sort
...
left

refers to the left subtree pointer of the structure s, and
s
...

In general, a member of a union may not be inspected unless the value of the union has been
assigned using the same member
...
For example, the following is a legal fragment:
union {
struct {
int type;
} n;
struct {
int type;
int intnode;
} ni;
struct {
int type;
float floatnode;
} nf;
} u;

...
nf
...
nf
...
14;

...
n
...
sin(u
...
floatnode)
...
8
...
The form of an enumeration specifier borrows from that of structures and
unions
...
If no enumerations with = appear, then the values of the
corresponding constants begin at 0 and increase by 1 as the declaration is read from left to

174
right
...

Enumerator names in the same scope must all be distinct from each other and from ordinary
variable names, but the values need not be distinct
...
The rules for enum-specifiers with and
without tags and lists are the same as those for structure or union specifiers, except that
incomplete enumeration types do not exist; the tag of an enum-specifier without an
enumerator list must refer to an in-scope specifier with a list
...


A
...
5 Declarators
Declarators have the syntax:
declarator:
pointeropt direct-declarator
direct-declarator:
identifier
(declarator)
direct-declarator [ constant-expressionopt ]
direct-declarator ( parameter-type-list )
direct-declarator ( identifier-listopt )
pointer:
* type-qualifier-listopt
* type-qualifier-listopt pointer
type-qualifier-list:
type-qualifier
type-qualifier-list type-qualifier
The structure of declarators resembles that of indirection, function, and array expressions; the
grouping is the same
...
8
...
Each
declarator declares a unique main identifier, the one that appears as the first alternative of the
production for direct-declarator
...
A declarator is read as an assertion that
when its identifier appears in an expression of the same form as the declarator, it yields an
object of the specified type
...
A
...
2) and a particular
declarator, a declaration has the form `T D,'where T is a type and D is a declarator
...

In a declaration T D where D is an unadored identifier, the type of the identifier is T
...
The parentheses do not alter the
type, but may change the binding of complex declarators
...
8
...
1 Pointer Declarators
In a declaration T D where D has the form
*

type-qualifier-listopt D1

and the type of the identifier in the declaration T D1 is `type-modifier T,'
`
'the type of the
`
'
identifier of D is `type-modifier type-qualifier-list pointer to T
...

For example, consider the declaration
int *ap[];
ap[] plays the

Here,
role of D1; a declaration `int ap[]'(below) would give ap the type
`
'
`array of int,'the type-qualifier list is empty, and the type-modifier is `array of
...
'
`
'
As other examples, the declarations
int i, *pi, *const cpi = &i;
const int ci = 3, *pci;
declare an integer i and a pointer to an integer pi
...
The integer ci is constant, and may not be changed (though it may be
initialized, as here
...

A
...
6
...
'If the constant-expression is present, it must have
`
'
integral type, and value greater than 0
...

An array may be constructed from an arithmetic type, from a pointer, from a structure or
union, or from another array (to generate a multi-dimensional array)
...

This implies that for a multi-dimensional array, only the first dimension may be missing
...
A
...
2), or by initializing it (Par
...
8
...
For example,
float fa[17], *afp[17];
declares an array of float numbers and
static int x3d[3][5][7];

an array of pointers to float numbers
...
In complete detail,
x3d is an array of three items: each item is an array of five arrays; each of the latter arrays is
an array of seven integers
...
The first three have type `array,' the last has type
`
'
,
int
...


176
The array subscripting operation is defined so that E1[E2] is identical to *(E1+E2)
...

Because of the conversion rules that apply to + and to arrays (Pars
...
6, A
...
1, A
...
7), if E1
is an array and E2 an integer, then E1[E2] refers to the E2-th member of E1
...
The first subexpression
x3d[i][j] is converted by Par
...
7
...
A
...
7, the
`
'
addition involves multiplication by the size of an integer
...

A
...
6
...
'
The syntax of the parameters is
parameter-type-list:
parameter-list
parameter-list ,
...
As a
special case, the declarator for a new-style function with no parameters has a parameter list
consisting soley of the keyword void
...
'
`
'
,
then the function may accept more arguments than the number of parameters explicitly
described, see Par
...
7
...
2
...
A
...
1
...
Similarly, if the declarators in the parameter
declarations contain identifiers and the function declarator does not head a function
definition, the identifiers go out of scope immediately
...
A
...
8
...
'
`
'The
parameters (if present) have the form

177
identifier-list:
identifier
identifier-list , identifier
In the old-style declarator, the identifier list must be absent unless the declarator is used in the
head of a function definition (Par
...
10
...
No information about the types of the parameters
is supplied by the declaration
...
In none of these are the parameter types
specified; they are old-style
...
The parameter names are effectively comments
...


Function declarators with parameter prototypes are, by far, the most important language change
introduced by the ANSI standard
...
Some
syntactic ugliness was required for the sake of compatibility, namely void as an explicit marker of
new-style functions without parameters
...
'for variadic functions is also new, and, together with the macros in the
`
'
standard header ...

These notations were adapted from the C++ language
...
8
...
The initializer is preceded by =, and is either an expression, or a list of
initializers nested in braces
...

initializer:
assignment-expression
{ initializer-list }
{ initializer-list , }
initializer-list:
initializer
initializer-list , initializer
All the expressions in the initializer for a static object or array must be constant expressions
as described in Par
...
7
...
The expressions in the initializer for an auto or register object
or array must likewise be constant expressions if the initializer is a brace-enclosed list
...

The first edition did not countenance initialization of automatic structures, unions, or arrays
...


A static object not explicitly initialized is initialized as if it (or its members) were assigned
the constant 0
...


178
The initializer for a pointer or an object of arithmetic type is a single expression, perhaps in
braces
...

The initializer for a structure is either an expression of the same type, or a brace-enclosed list
of initializers for its members in order
...
If there are fewer initializers in the list than members of the structure, the trailing
members are initialized with 0
...
Unnamed
bit-field members are ignored,and are not initialized
...
If the array
has unknown size, the number of initializers determines the size of the array, and its type
becomes complete
...

As a special case, a character array may be initialized by a string literal; successive characters
of the string initialize successive members of the array
...
A
...
6) may initialize an array of type wchar_t
...

The initializer for a union is either a single expression of the same type, or a brace-enclosed
initializer for the first member of the union
...
The `first-member'rule is clumsy, but is hard to
`
'
generalize without new syntax
...


An aggregate is a structure or array
...
Braces may be elided in the initialization as follows: if
the initializer for an aggregate' member that itself is an aggregate begins with a left brace,
s
then the succeding comma-separated list of initializers initializes the members of the
subaggregate; it is erroneous for there to be more initializers than members
...

For example,
int x[] = { 1, 3, 5 };

declares and initializes x as a 1-dimensional array with three members, since no size was
specified and there are three initializers
...
Likewise the next two lines initialize y[1] and
y[2]
...

Precisely the same effect could have been achieved by
float y[4][3] = {
1, 3, 5, 2, 4, 6, 3, 5, 7
};

179
The initializer for y begins with a left brace, but that for y[0] does not; therefore three
elements from the list are used
...
Also,
float y[4][3] = {
{ 1 }, { 2 }, { 3 }, { 4 }
};
initializes the first column of y (regarded as

a two-dimensional array) and leaves the rest 0
...


A
...
8 Type names
In several contexts (to specify type conversions explicitly with a cast, to declare parameter
types in function declarators, and as argument of sizeof) it is necessary to supply the name
of a data type
...

type-name:
specifier-qualifier-list abstract-declaratoropt
abstract-declarator:
pointer
pointeropt direct-abstract-declarator
direct-abstract-declarator:
( abstract-declarator )
direct-abstract-declaratoropt [constant-expressionopt]
direct-abstract-declaratoropt (parameter-type-listopt)
It is possible to identify uniquely the location in the abstract-declarator where the identifier
would appear if the construction were a declarator in a declaration
...
For example,
int
int
int
int
int
int

*
*[3]
(*)[]
*()
(*[])(void)

name respectively the types `integer,'`pointer to integer,'`array of 3 pointers to integers,'
`
'`
'`
'
`pointer to an unspecified number of integers,' `
`
'`function of unspecified parameters
returning pointer to integer,'and `array, of unspecified size, of pointers to functions with no
'
`
parameters each returning an integer
...
8
...
These identifiers are called typedef names
...
A
...
6)
...


180
For example, after
typedef long Blockno, *Blockptr;
typedef struct { double r, theta; } Complex;

the constructions

Blockno b;
extern Blockptr bp;
Complex z, *zp;

are legal declarations
...

typedef does not introduce new types, only synonyms for types that could be specified in
another way
...


Typedef names may be redeclared in an inner scope, but a non-empty set of type specifiers
must be given
...


A
...
10 Type Equivalence
Two type specifier lists are equivalent if they contain the same set of type specifiers, taking
into account that some specifiers can be implied by others (for example, long alone implies
long int)
...

Two types are the same if their abstract declarators (Par
...
8
...
Array sizes and function parameter types are significant
...
9 Statements
Except as described, statements are executed in sequence
...
They fall into several groups
...
9
...

labeled-statement:
identifier : statement
case constant-expression : statement
default : statement
A label consisting of an identifier declares the identifier
...
The scope of the identifier is the current function
...

See Par
...
11
...


181
Case labels and default labels are used with the switch statement (Par
...
9
...
The constant
expression of case must have integral type
...


A
...
2 Expression Statement
Most statements are expression statements, which have the form
expression-statement:
expressionopt;
Most expression statements are assignments or function calls
...
If the expression is missing,
the construction is called a null statement; it is often used to supply an empty body to an
iteration statement to place a label
...
9
...
The body of a function definition is a compound statement
...
A
...
1), after which it resumes its force
...
These rules apply to identifiers in the same
name space (Par
...
11); identifiers in different name spaces are treated as distinct
...
If a jump into the block is executed, these
initializations are not performed
...


A
...
4 Selection Statements
Selection statements choose one of several flows of control
...
In the second form, the second substatement is executed if the expression is 0
...

The switch statement causes control to be transferred to one of several statements depending
on the value of an expression, which must have integral type
...
Any statement within the substatement may be labeled with
one or more case labels (Par
...
9
...
The controlling expression undergoes integral
promotion (Par
...
6
...
No two of
these case constants associated with the same switch may have the same value after
conversion
...
Switches
may be nested; a case or default label is associated with the smallest switch that contains it
...
If one of the case constants is equal to the value of the
expression, control passes to the statement of the matched case label
...
If no case matches, and if there is no default, then none of the substatements of
the swtich is executed
...


A
...
5 Iteration Statements
Iteration statements specify looping
...

With while, the test, including all side effects from the expression, occurs before each
execution of the statement; with do, the test follows each iteration
...
There is no restriction on its type
...
The third expression is evaluated after each iteration, and thus specifies a reinitialization for the loop
...
Side-effects from each
expression are completed immediately after its evaluation
...
A missing second expression makes the
implied test equivalent to testing a non-zero element
...
9
...

jump-statement:
goto identifier;
continue;
break;
return expressionopt;

183
In the goto statement, the identifier must be a label (Par
...
9
...
Control transfers to the labeled statement
...
It causes control to
pass to the loop-continuation portion of the smallest enclosing such statement
...
) {

...

contin: ;
} while (
...
) {

...


A break statement may appear only in an iteration statement or a switch statement, and
terminates execution of the smallest enclosing such statement; control passes to the statement
following the terminated statement
...
When return is followed by an
expression, the value is returned to the caller of the function
...

Flowing off the end of a function is equivalent to a return with no expression
...


A
...

translation-unit:
external-declaration
translation-unit external-declaration
external-declaration:
function-definition
declaration
The scope of external declarations persists to the end of the translation unit in which they are
declared, just as the effect of declarations within the blocks persists to the end of the block
...


A
...
1 Function Definitions
Function definitions have the form
function-definition:
declaration-specifiersopt declarator declaration-listopt compound-statement
The only storage-class specifiers allowed among the declaration specifiers are extern or
static; see Par
...
11
...

A function may return an arithmetic type, a structure, a union, a pointer, or void, but not a
function or an array
...
A
...
6
...

direct-declarator ( parameter-type-list )
direct-declarator ( identifier-listopt )

184
where the direct-declarator is an identifier or a parenthesized identifier
...

In the first form, the definition is a new-style function, and its parameters, together with their
types, are declared in its parameter type list; the declaration-list following the function'
s
declarator must be absent
...
If the parameter type list ends with `,
...
h> and described in Appendix B must be used to refer to the extra
arguments
...

In the second form, the definition is old-style: the identifier list names the parameters, while
the declaration list attributes types to them
...
The declaration list must declare only parameters named in the list,
initialization is not permitted, and the only storage-class specifier possible is register
...
If a parameter is declared to have type `array of type,'
`
'the
declaration is adjusted to read `pointer to type;'similarly, if a parameter is declared to have
`
'
type `function returning type,'
`
'the declaration is adjusted to read `pointer to function
`
returning type
...
A
...
3
...

New-style function definitions are new with the ANSI standard
...
The difference becomes noticable when a pointer to a parameter is generated within a
function
...
} is the block giving the code for the function
...
*/
}
where now int max(a, b, c)

the parameters
...
10
...

The term `external'refers to their location outside functions, and is not directly connected
`
'
with the extern keyword; the storage class for an externally-declared object may be left
empty, or it may be specified as extern or static
...


185
Two declarations for an object or function are deemed to agree in type under the rule
discussed in Par
...
8
...
In addition, if the declarations differ because one type is an
incomplete structure, union, or enumeration type (Par
...
8
...
Moreover, if
one type is an incomplete array type (Par
...
8
...
2) and the other is a completed array type, the
types, if otherwise identical, are also taken to agree
...

If the first external declarator for a function or object includes the static specifier, the
identifier has internal linkage; otherwise it has external linkage
...
11
...

An external declaration for an object is a definition if it has an initializer
...
If a definition for an object appears in a translation unit, any tentative
definitions are treated merely as redundant declarations
...

Each object must have exactly one definition
...
For objects with external linkage, it applies to the entire program
...
Some implementations relax it by generalizing the notion of
tentative definition
...
If a definition occurs somewhere in the program, then the tentative definitions become
merely declarations, but if no definition appears, then all its tentative definitions become a definition
with initializer 0
...
11 Scope and Linkage
A program need not all be compiled at one time: the source text may be kept in several files
containing translation units, and precompiled routines may be loaded from libraries
...

Therefore, there are two kinds of scope to consider: first, the lexical scope of an identifier
which is the region of the program text within which the identifier' characteristics are
s
understood; and second, the scope associated with objects and functions with external
linkage, which determines the connections between identifiers in separately compiled
translation units
...
11
...
These classes are: objects, functions, typedef
constants; labels; tags of structures or unions, and enumerations; and
structure or union individually
...
Labels did not
previously have their own name space; tags of structures and unions each had a separate space, and in
some implementations enumerations tags did as well; putting different kinds of tags into the same space
is a new restriction
...
This rule has been common practice for several years
...
The

186
scope of a parameter of a function definition begins at the start of the block defining the
function, and persists through the function; the scope of a parameter in a function declaration
ends at the end of the declarator
...
The scope of a label is
the whole of the function in which it appears
...

If an identifier is explicitly declared at the head of a block, including the block constituting a
function, any declaration of the identifier outside the block is suspended until the end of the
block
...
11
...
All declarations for the same object or function identifier with external linkage refer to
the same thing, and the object or function is shared by the entire program
...
A
...
2, the first external declaration for an identifier gives the identifier
internal linkage if the static specifier is used, external linkage otherwise
...
If it does include extern, and an external declaration
for is active in the scope surrounding the block, then the identifier has the same linkage as the
external declaration, and refers to the same object or function; but if no external declaration is
visible, its linkage is external
...
12 Preprocessing
A preprocessor performs macro substitution, conditional compilation, and inclusion of named
files
...
The syntax of these lines is independent of the rest of the language; they may
appear anywhere and have effect that lasts (independent of scope) until the end of the
translation unit
...
A
...
2 for how to adjoin lines)
...
A
...
4); in addition,
any character not otherwise defined is taken as a token
...

Preprocessing itself takes place in several logically successive phases that may, in a particular
implementation, be condensed
...
First, trigraph sequences as described in Par
...
12
...

Should the operating system environment require it, newline characters are introduced
between the lines of the source file
...
Each occurrence of a backslash character \ followed by a newline is deleted, this
splicing lines (Par
...
12
...

3
...
Then preprocessing directives are obeyed, and macros
(Pars
...
12
...
12
...

4
...
A
...
5
...
2
...


187
5
...


A
...
1 Trigraph Sequences
The character set of C source programs is contained within seven-bit ASCII, but is a superset
of the ISO 646-1983 Invariant Code Set
...
This replacement occurs before any other processing
...


[
]
|

??<
??>
??-

{
}
~

Trigraph sequences are new with the ANSI standard
...
12
...
This occurs before division into tokens
...
12
...

A second #define for the same identifier is erroneous unless the second token sequence is
identical to the first, where all white space separations are taken to be equivalent
...
As with the first form, leading and trailing white space
arround the token sequence is discarded, and the macro may be redefined only with a
definition in which the number and spelling of parameters, and the token sequence, is
identical
...
It is not erroneous to apply
s
an unknown identifier
...
The arguments of the call are the
comma-separated token sequences; commas that are quoted or protected by nested
parentheses do not separate arguments
...
The number of arguments in the call must match the number of parameters in the
definition
...
Then the token sequence resulting from each argument is substituted for each unquoted
occurrence of the corresponding parameter' identifier in the replacement token sequence of
s
the macro
...

Two special operators influence the replacement process
...
A \ character is inserted before each " or \
character that appears surrounding, or inside, a string literal or character constant in the
argument
...
The effect is
undefined if invalid tokens are produced, or if the result depends on the order of processing of
the ## operators
...

In both kinds of macro, the replacement token sequence is repeatedly rescanned for more
defined identifiers
...

Even if the final value of a macro expansion begins with with #, it is not taken to be a
preprocessing directive
...
The most important change is the addition of the # and ## operators, which make
quotation and concatenation admissible
...
(See example below
...
Unlike a
function to do the same thing, the arguments and returned value may have any arithmetic type
or even be pointers
...

Given the definition
the

#define tempfile(dir)
#dir "%s"
macro call tempfile(/usr/tmp) yields
"/usr/tmp" "%s"

which will subsequently be catenated into a single string
...
However, the call cat(cat(1,2),3) is undefined:
the presence of ## prevents the arguments of the outer call from being expanded
...
If a second level of macro definition is introduced,
#define xcat(x, y)

cat(x,y)

189
things work more smoothly; xcat(xcat(1, 2), 3) does produce 123, because the
expansion of xcat itself does not involve the ## operator
...


A
...
4 File Inclusion
A control line of the form
# include

causes the replacement of that line by the entire contents of the file filename
...
The named file is searched for in a sequence of implementation-defined
places
...
The effect of using ', \,
or /* in the filename remains undefined, but > is permitted
...
> or "
...

#include

files may be nested
...
12
...

preprocessor-conditional:
if-line text elif-parts else-partopt #endif
if-line:

# if constant-expression
# ifdef identifier
# ifndef identifier

elif-parts:
elif-line text
elif-partsopt
elif-line:

# elif constant-expression

else-part:
else-line text
else-line:
#else

190
Each of the directives (if-line, elif-line, else-line, and #endif) appears alone on a line
...
The text following the successful directive line is treated normally
...
Once a successful #if or #elif line has been found and its text
processed, succeeding #elif and #else lines, together with their text, are discarded
...

Text controlled by inactive arms of the conditional is ignored except for checking the nesting
of conditionals
...

Moreover, any expressions of the form
defined

identifier

defined

(identifier)

or

are replaced, before scanning for macros, by 1L if the identifier is defined in the preprocessor,
and by 0L if not
...
Finally,
each integer constant is considered to be suffixed with L, so that all arithmetic is taken to be
long or unsigned long
...
A
...
19) is restricted: it must be integral, and may not
contain sizeof, a cast, or an enumeration constant
...

#elif is new since the first edition, although it has been available is some preprocessors
...


A
...
6 Line Control
For the benefit of other preprocessors that generate C programs, a line in one of the forms
# line
# line

constant "filename"
constant

causes the compiler to believe, for purposes of error diagnostics, that the line number of the
next source line is given by the decimal integer constant and the current input file is named
by the identifier
...

Macros in the line are expanded before it is interpreted
...
12
...


A
...
8 Pragmas
A control line of the form
# pragma

token-sequenceopt

causes the preprocessor to perform an implementation-dependent action
...


A
...
9 Null directive
A control line of the form
#

has no effect
...
12
...
They, and also
the preprocessor expansion operator defined, may not be undefined or redefined
...

__FILE__ A string literal containing the name of the file being compiled
...
It is intended that this identifier be defined to be 1 only in
__STDC__
standard-conforming implementations
...


A
...
It has exactly the same content, but is in different order
...
This grammar can be transformed mechanically into
input acceptable for an automatic parser-generator
...
With one further
change, namely deleting the production typedef-name: identifier and making typedef-name a
terminal symbol, this grammar is acceptable to the YACC parser-generator
...

translation-unit:
external-declaration
translation-unit external-declaration
external-declaration:
function-definition
declaration
function-definition:
declaration-specifiersopt declarator declaration-listopt compound-statement
declaration:
declaration-specifiers init-declarator-listopt;

192
declaration-list:
declaration
declaration-list declaration
declaration-specifiers:
storage-class-specifier declaration-specifiersopt
type-specifier declaration-specifiersopt
type-qualifier declaration-specifiersopt
storage-class specifier: one of
auto register static extern typedef

type specifier: one of
void char short int long float double signed
unsigned struct-or-union-specifier enum-specifier typedef-name

type-qualifier: one of
const volatile

struct-or-union-specifier:
struct-or-union identifieropt { struct-declaration-list }
struct-or-union identifier
struct-or-union: one of
struct union

struct-declaration-list:
struct declaration
struct-declaration-list struct declaration
init-declarator-list:
init-declarator
init-declarator-list, init-declarator
init-declarator:
declarator
declarator = initializer
struct-declaration:
specifier-qualifier-list struct-declarator-list;
specifier-qualifier-list:
type-specifier specifier-qualifier-listopt
type-qualifier specifier-qualifier-listopt
struct-declarator-list:
struct-declarator
struct-declarator-list , struct-declarator
struct-declarator:
declarator
declaratoropt : constant-expression
enum-specifier:
enum identifieropt { enumerator-list }
enum identifier

193
enumerator-list:
enumerator
enumerator-list , enumerator
enumerator:
identifier
identifier = constant-expression
declarator:
pointeropt direct-declarator
direct-declarator:
identifier
(declarator)
direct-declarator [ constant-expressionopt ]
direct-declarator ( parameter-type-list )
direct-declarator ( identifier-listopt )
pointer:
* type-qualifier-listopt
* type-qualifier-listopt pointer
type-qualifier-list:
type-qualifier
type-qualifier-list type-qualifier
parameter-type-list:
parameter-list
parameter-list ,
...
identifier
postfix-expression->+identifier
postfix-expression++
postfix-expression-primary-expression:
identifier
constant
string
(expression)
argument-expression-list:
assignment-expression
assignment-expression-list , assignment-expression
constant:
integer-constant
character-constant
floating-constant
enumeration-constant
The following grammar for the preprocessor summarizes the structure of control lines, but is
not suitable for mechanized parsing
...

control-line:
# define identifier token-sequence
# define identifier(identifier,
...
The standard library
is not part of the C language proper, but an environment that supports standard C will provide
the function declarations and type and macro definitions of this library
...

The functions, types and macros of the standard library are declared in standard headers:
...
h>
...
h>
...
h>

A header can be accessed by
#include

...
h>
...
h>
...
h>

...
h>
...
A header must be included
outside of any external declaration or definition and before any use of anything it declares
...

External identifiers that begin with an underscore are reserved for use by the library, as are all
other identifiers that begin with an underscore and an upper-case letter or another underscore
...
1 Input and Output: ...
h> represent nearly one
third of the library
...
The library supports text streams and binary streams, although on some systems,
notably UNIX, these are identical
...
An environment may need to convert a text
stream to or from some other representation (such as mapping '\n' to carriage return and
linefeed)
...

A stream is connected to a file or device by opening it; the connection is broken by closing
the stream
...
We will use `file pointer'
`
'and `stream'
`
'
interchangeably when there is no ambiguity
...


B
...
1 File Operations
The following functions deal with operations on files
...

FILE *fopen(const char *filename, const char *mode)
fopen opens the named file, and returns a stream, or NULL if the attempt
values for mode include:
"r" open text file for reading
"w" create text file for writing; discard previous contents if any
"a" append; open or create text file for writing at end of file
"r+" open text file for update (i
...
, reading and writing)

fails
...
If the mode includes
b after the initial letter, as in "rb" or "w+b", that indicates a binary file
...
At most FOPEN_MAX files may be open at once
...
It
returns stream, or NULL if an error occurs
...

int fflush(FILE *stream)
On an output stream, fflush causes any buffered but unwritten data to be written; on
an input stream, the effect is undefined
...
fflush(NULL) flushes all output streams
...
It returns EOF if any

errors occurred, and zero otherwise
...
It
returns non-zero if the attempt fails
...

FILE *tmpfile(void)
tmpfile creates a temporary file of mode "wb+" that will be automatically removed
when closed or when the program terminates normally
...

char *tmpnam(char s[L_tmpnam])
tmpnam(NULL) creates a string that is not the name of an existing file, and returns a
pointer to an internal static array
...
tmpnam
generates a different name each time it is called; at most TMP_MAX different names are
guaranteed during execution of the program
...


int setvbuf(FILE *stream, char *buf, int mode, size_t size)
setvbuf controls buffering for the stream; it must be called before reading, writing or
any other operation
...
If buf is not NULL, it will be used as the buffer,
otherwise a buffer will be allocated
...
setvbuf returns

non-zero for any error
...
Otherwise, setbuf
to (void) setvbuf(stream, buf, _IOFBF, BUFSIZ)
...
1
...

int fprintf(FILE *stream, const char *format,
...


is the number of characters written, or negative if an error occurred
...
Each conversion specification begins with the

200
character % and ends with a conversion character
...


o

+,

which specifies that the number will always be printed with a sign
...


o

0:

o

#, which specifies an alternate output form
...
For x or X, 0x or 0X will be prefixed to a non-zero result
...


for numeric conversions, specifies padding to the field width with leading
zeros
...
The converted argument will be printed
in a field at least this wide, and wider if necessary
...
The padding character is
normally space, but is 0 if the zero padding flag is present
...




A number, the precision, that specifies the maximum number of characters to be
printed from a string, or the number of digits to be printed after the decimal point for
e, E, or f conversions, or the number of significant digits for g or G conversion, or the
number of digits to be printed for an integer (leading 0s will be added to make up the
necessary width)
...
`h'indicates that the corresponding argument
`'
is to be printed as a short or unsigned short; `l'indicates that the argument is a
`'
long or unsigned long, `L'indicates that the argument is a long double
...

The conversion characters and their meanings are shown in Table B
...
If the character after
the % is not a conversion character, the behavior is undefined
...
1 Printf Conversions
Characte
r
d,i
o
x,X
u
c
s

Argument type; Printed As
int;

signed decimal notation
...

unsigned int; unsigned hexadecimal notation (without a leading 0x or 0X),
using abcdef for 0x or ABCDEF for 0X
...

int; single character, after conversion to unsigned char
char *; characters from the string are printed until a '\0' is reached or until the
number of characters indicated by the precision have been printed
...
ddd, where the number of d' is
s
given by the precision
...

double; decimal notation of the form [-]m
...
ddddddE+/xx, where the number of d' is specified by the precision
...

double; %e or %E is used if the exponent is less than -4 or greater than or equal
to the precision; otherwise %f is used
...

void *; print as a pointer (implementation-dependent representation)
...
No argument is converted
...
)
printf(
...

int sprintf(char *s, const char *format,
...
s must be big enough to hold the result
...

int vprintf(const char *format, va_list arg)
int vfprintf(FILE *stream, const char *format, va_list arg)
int vsprintf(char *s, const char *format, va_list arg)
The functions vprintf, vfprintf, and vsprintf are equivalent to the corresponding
printf functions, except that the variable argument list is replaced by arg, which has
been initialized by the va_start macro and perhaps va_arg calls
...
h> in Section B
...


B
...
3 Formatted Input
The scanf function deals with formatted input conversion
...
)
fscanf reads from stream under control of format, and assigns

converted values through
subsequent arguments, each of which must be a pointer
...

fscanf returns EOF if end of file or an error occurs before any conversion; otherwise it
returns the number of input items converted and assigned
...
The format string may contain:


Blanks or tabs, which are not ignored
...




Conversion specifications, consisting of a %, an optional assignment suppression
character *, an optional number specifying a maximum field width, an optional h, l,
or L indicating the width of the target, and a conversion character
...
Normally the
result is placed in the variable pointed to by the corresponding argument
...
An input field is defined as a string of non-white space characters; it
extends either to the next white space character or until the field width, if specified, is
exhausted
...
(White space characters are blank, tab, newline, carriage return,
vertical tab, and formfeed
...
The corresponding
argument must be a pointer
...
2
...
The
conversion characters e, f, and g may be preceded by l if a pointer to double rather than
float is in the argument list, and by L if a pointer to a long double
...
2 Scanf Conversions
Characte
r
d
i
o
u
x

c

s

e,f,g
p
n
[
...
]
%

Input Data; Argument type
decimal integer; int*
integer; int*
...

octal integer (with or without leading zero); int *
...

hexadecimal integer (with or without leading 0x or 0X); int*
...
The next input characters are placed in the indicated array, up
to the number given by the width field; the default is 1
...
The
normal skip over white space characters is suppressed in this case; to read the
next non-white space character, use %1s
...

floating-point number; float *
...

pointer value as printed by printf("%p");, void *
...

No input is read
...

matches the longest non-empty string of input characters from the set between
brackets; char *
...
] includes ] in the set
...
A '\0' is added
...

literal %; no assignment is made
...
)
scanf(
...

int sscanf(const char *s, const char *format,
...
) is equivalent to scanf(
...


that the input characters are

B
...
4 Character Input and Output Functions
int fgetc(FILE *stream)
fgetc returns the next character of stream
int), or EOF if end of file or error occurs
...
fgets
returns s, or NULL if end of file or error occurs
...
It returns
the character written, or EOF for error
...

int getc(FILE *stream)
getc is equivalent to fgetc except that if it is a macro, it may evaluate stream

than once
...

char *gets(char *s)
gets reads the next input line into the array s; it replaces the terminating newline with
'\0'
...

int putc(int c, FILE *stream)
putc is equivalent to fputc except that if it is a macro, it may evaluate stream more

than once
...

int puts(const char *s)
puts writes the string s and a newline to stdout
...


It returns EOF if an error occurs,

int ungetc(int c, FILE *stream)
ungetc pushes c (converted to an unsigned char)

back onto stream, where it will be
returned on the next read
...

EOF may not be pushed back
...


B
...
5 Direct Input and Output Functions
size_t fread(void *ptr, size_t size, size_t nobj, FILE *stream)
fread reads from stream into the array ptr at most nobj objects of size size
...
feof
and ferror must be used to determine status
...
It returns the
number of objects written, which is less than nobj on error
...
1
...
For a binary file, the position is set to offset
characters from origin, which may be SEEK_SET (beginning), SEEK_CUR (current
position), or SEEK_END (end of file)
...
fseek returns
non-zero on error
...

void rewind(FILE *stream)
rewind(fp) is equivalent to fseek(fp, 0L, SEEK_SET); clearerr(fp)
...
The type fpos_t is suitable for recording such values
...


int fsetpos(FILE *stream, const fpos_t *ptr)

204
positions stream at the position recorded by fgetpos in *ptr
...

fsetpos

B
...
7 Error Functions
Many of the functions in the library set status indicators when error or end of file occur
...
In addition, the integer expression errno
(declared in ...

void clearerr(FILE *stream)
clearerr clears the end of file and error indicators for stream
...

int ferror(FILE *stream)
ferror returns non-zero if the error indicator for stream is set
...
3
...
2 Character Class Tests: ...
h> declares functions for testing characters
...
The functions return non-zero (true) if the argument c satisfies the
condition described, and zero if not
...

In addition, there are two functions that convert the case of letters:
int tolower(c)
int toupper(c)

If c is an
toupper(c)

convert c to lower case
convert c to upper case

upper-case letter, tolower(c) returns the corresponding lower-case letter,
returns the corresponding upper-case letter; otherwise it returns c
...
3 String Functions: ...
h>
...
Except for memmove,
the behavior is undefined if copying takes place between overlapping objects
...


205
In the following table, variables s and t are of type char *; cs and ct are of type const
char *; n is of type size_t; and c is an int converted to char
...

copy at most n characters of string ct to s; return s
...

concatenate string ct to end of string s; return s
...

compare string cs to string ct, return <0 if cs0
int strcmp(cs,ct)
if cs>ct
...

char *strchr(cs,c) return pointer to first occurrence of c in cs or NULL if not present
...

size_t
return length of prefix of cs consisting of characters in ct
...

return pointer to first occurrence in string cs of any character string
ct, or NULL if not present
...

size_t strlen(cs)
return length of cs
...

strtok searches s for tokens delimited by characters from ct; see
char *strtok(s,ct)
below
...
The first call in a sequence has a non-NULL s, it finds the first token in s consisting of
characters not in ct; it terminates that by overwriting the next character of s with '\0' and
returns a pointer to the token
...
strtok returns
NULL when no further token is found
...

The mem
...
In the following table, s and t are of type void *; cs and ct
are of type const void *; n is of type size_t; and c is an int converted to an unsigned
char
...

same as memcpy except that it works even if the objects overlap
...

return pointer to first occurrence of character c in cs, or NULL if not
present among the first n characters
...


B
...
h>
The header ...

The macros EDOM and ERANGE (found in ...
A domain error occurs if an argument is outside the domain over which the function is
defined
...

A range error occurs if the result of the function cannot be represented as a double
...
If the result underflows, the function returns zero; whether errno is set to ERANGE is
implementation-defined
...


double
...

cos-1(x) in range [0,pi], x in [-1,1]
...

tan-1(y/x) in range [-pi,pi]
...

base 10 logarithm log10(x), x>0
...
A domain error occurs if x=0 and y<=0, or if x<0 and y is not an
pow(x,y)
integer
...

ceil(x)
smallest integer not less than x, as a double
...

fabs(x)
absolute value |x|
ldexp(x,n)
x*2n
splits x into a normalized fraction in the interval [1/2,1) which is returned,
frexp(x, int
and a power of 2, which is stored in *exp
...

modf(x, double splits x into integral and fractional parts, each with the same sign as x
...

floating-point remainder of x/y, with the same sign as x
...

sin(x)
cos(x)
tan(x)
asin(x)
acos(x)
atan(x)
atan2(y,x)
sinh(x)
cosh(x)
tanh(x)
exp(x)
log(x)
log10(x)

B
...
h>
The header ...
double atof(const char *s)
atof converts s to double; it is equivalent to strtod(s, (char**)NULL)
...

long atol(const char *s)
converts s to long; it is equivalent to strtol(s, (char**)NULL, 10)
...
If the answer would
overflow, HUGE_VAL is returned with the proper sign; if the answer would underflow,
zero is returned
...

long strtol(const char *s, char **endp, int base)
strtol converts the prefix of s to long, ignoring leading white space; it stores a
pointer to any unconverted suffix in *endp unless endp is NULL
...
If base is
zero, the base is 8, 10, or 16; leading 0 implies octal and leading 0x or 0X
hexadecimal
...
If the answer would overflow, LONG_MAX or LONG_MIN is
returned, depending on the sign of the result, and errno is set to ERANGE
...

int rand(void)
rand returns a pseudo-random integer in the range 0 to RAND_MAX, which is at

32767
...


error
least

for a new sequence of pseudo-random numbers
...
The space is initialized to zero bytes
...
The space is uninitialized
...
The contents will be
unchanged up to the minimum of the old and new sizes
...
realloc returns a pointer to the new space, or NULL if the
request cannot be satisfied, in which case *p is unchanged
...
p must be a
pointer to space previously allocated by calloc, malloc, or realloc
...

void exit(int status)
exit causes normal program termination
...
How status is returned to the environment is implementationdependent, but zero is taken as successful termination
...


int atexit(void (*fcn)(void))
atexit registers the function fcn

to be called when the program terminates normally;
it returns non-zero if the registration cannot be made
...
If s is NULL, system
returns non-zero if there is a command processor
...


char *getenv(const char *name)
getenv returns the environment

string associated with name, or NULL if no string
exists
...


void *bsearch(const void *key, const void *base,
size_t n, size_t size,
int (*cmp)(const void *keyval, const void *datum))
bsearch searches base[0]
...
The function
cmp must return negative if its first argument (the search key) is less than its second (a
table entry), zero if equal, and positive if greater
...
bsearch returns a pointer to a matching item, or NULL if none exists
...
base[n-1] of objects of size
size
...

int abs(int n)
abs returns the absolute value of its int argument
...

div_t div(int num, int denom)
div computes the quotient and remainder of num/denom
...

ldiv_t ldiv(long num, long denom)
ldiv computes the quotient and remainder of num/denom
...


B
...
h>
The assert macro is used to add diagnostics to programs:
void assert(int expression)

If expression is zero when
assert(expression)

is executed, the assert macro will print on stderr a message, such as
Assertion failed:

expression, file filename, line nnn

It then calls abort to terminate execution
...

If NDEBUG is defined at the time ...


B
...
h>
The header ...

Suppose lastarg is the last named parameter of a function f with a variable number of
arguments
...


B
...
h>

209
The declarations in ...

int setjmp(jmp_buf env)
The macro setjmp saves

state information in env for use by longjmp
...
A
call to setjmp can only occur in certain contexts, basically the test of if, switch, and
loops, and only in simple relational expressions
...
The function containing the setjmp

must not have terminated
...


B
...
h>
The header ...

void (*signal(int sig, void (*handler)(int)))(int)
signal determines how subsequent signals will be handled
...
Valid signals include
SIGABRT
abnormal termination, e
...
, from abort
SIGFPE
arithmetic error, e
...
, zero divide or overflow
SIGILL
illegal function image, e
...
, illegal instruction
SIGINT
interactive attention, e
...
, interrupt
SIGSEGV
illegal storage access, e
...
, access outside memory limits
SIGTERM
termination request sent to this program
signal

occurs
...
If the handler returns, execution
will resume where it was when the signal occurred
...

int raise(int sig)
raise sends the signal sig

to the program; it returns non-zero if unsuccessful
...
10 Date and Time Functions: ...
h> declares types and functions for manipulating date and time
...
clock_t and time_t are arithmetic types representing times, and struct tm
holds the components of a calendar time:
int tm_sec;
seconds after the minute (0,61)
int tm_min;
minutes after the hour (0,59)

210
int
int
int
int
int
int
int

tm_hour;
tm_mday;
tm_mon;
tm_year;
tm_wday;
tm_yday;
tm_isdst;

hours since midnight (0,23)
day of the month (1,31)
months since January (0,11)
years since 1900
days since Sunday (0,6)
days since January 1 (0,365)
Daylight Saving Time flag

tm_isdst is positive if Daylight Saving Time is in effect, zero if not, and negative if the
information is not available
...
clock()/CLK_PER_SEC is a time in seconds
...
If tp is not
NULL, the return value is also assigned to *tp
...

time_t mktime(struct tm *tp)
mktime converts the local time in the structure *tp into calendar time in the same
representation used by time
...

mktime returns the calendar time or -1 if it cannot be represented
...


char *asctime(const struct tm *tp)
asctimethe form
Sun Jan 3 15:14:13 1988\n\0
char *ctime(const time_t *tp)
ctime converts the calendar time *tp to local time; it is equivalent
to
asctime(localtime(tp))
struct tm *gmtime(const time_t *tp)
gmtime converts the calendar time *tp into Coordinated Universal Time
(UTC)
...
The name gmtime has
historical significance
...

size_t strftime(char *s, size_t smax, const char *fmt, const struct tm *tp)
strftime formats date and time information from *tp into s according
to fmt, which is analogous to a printf format
...
Each %c is
replaced as described below, using values appropriate for the local
environment
...
strftime
returns the number of characters, excluding the '\0', or zero if more
than smax characters were produced
...

%A
full weekday name
...

%B
full month name
...

%d
day of the month (01-31)
...

%I
hour (12-hour clock) (01-12)
...

%m
month (01-12)
...


211
%p
%S
%U
%w
%W
%x
%X
%y
%Y
%Z
%%

local equivalent of AM or PM
...

week number of the year (Sunday as 1st day of week) (00-53)
...

week number of the year (Monday as 1st day of week) (00-53)
...

local time representation
...

year with century
...

%

B
...
h> and ...
h> defines constants for the sizes of integral types
...

CHAR_BIT
8
bits in a char
UCHAR_MAX or
CHAR_MAX
maximum value of char
SCHAR_MAX
CHAR_MIN
0 or SCHAR_MIN
maximum value of char
INT_MAX
32767
maximum value of int
INT_MIN
-32767
minimum value of int
LONG_MAX
2147483647
maximum value of long
LONG_MIN
-2147483647
minimum value of long
SCHAR_MAX +127
maximum value of signed char
SCHAR_MIN -127
minimum value of signed char
SHRT_MAX
+32767
maximum value of short
SHRT_MIN
-32767
minimum value of short
UCHAR_MAX 255
maximum value of unsigned char
UINT_MAX
65535
maximum value of unsigned int
ULONG_MAX 4294967295
maximum value of unsigned long
maximum value of unsigned
USHRT_MAX 65535
short
The names in the table below, a subset of ...
When a value is given, it represents the
minimum magnitude for the corresponding quantity
...

FLT_RADIX
2
radix of exponent, representation, e
...
, 2, 16
FLT_ROUNDS
floating-point rounding mode for addition
FLT_DIG
6
decimal digits of precision
FLT_EPSILON
1E-5
smallest number x such that 1
...
0
FLT_MANT_DIG
number of base FLT_RADIX in mantissa
FLT_MAX
1E+37
maximum floating-point number
FLT_MAX_EXP
maximum n such that FLT_RADIXn-1 is representable
FLT_MIN
1E-37
minimum normalized floating-point number
FLT_MIN_EXP
minimum n such that 10n is a normalized number
DBL_DIG
10
decimal digits of precision
DBL_EPSILON
1E-9
smallest number x such that 1
...
0
DBL_MANT_DIG
number of base FLT_RADIX in mantissa
DBL_MAX
1E+37
maximum double floating-point number
DBL_MAX_EXP
maximum n such that FLT_RADIXn-1 is representable
DBL_MIN
1E-37
minimum normalized double floating-point number
DBL_MIN_EXP
minimum n such that 10n is a normalized number

212

Appendix C - Summary of Changes
Since the publication of the first edition of this book, the definition of the C language has
undergone changes
...
Many of
the new facilities were announced in the documents accompanying compilers available from
AT&T, and have subsequently been adopted by other suppliers of C compilers
...
Their report was in part participated by
some commercial compilers even before issuance of the formal C standard
...
It treats only the language
itself, not its environment and library; although these are an important part of the standard,
there is little to compare with, because the first edition did not attempt to prescribe an
environment or library
...
Splicing of lines by \ is permitted
everywhere, not just in strings and macro definitions
...
A
...




The minimum significance of all internal identifiers increased to 31 characters; the
smallest mandated significance of identifiers with external linkage remains 6
monocase letters
...
)



Trigraph sequences introduced by ?? allow representation of characters lacking in
some character sets
...
A
...
1
...




New keywords (void, const, volatile, signed, enum) are introduced
...




New escape sequences, for use within character constants and string literals, are
defined
...
See Par
...
2
...
2
...

s



The standard introduces a larger set of suffixes to make the type of constants explicit:
U or L for integers, F or L for floating
...
A
...
5)
...




There is a notation for wide-character string literals and character constants; see
Par
...
2
...




Characters as well as other types, may be explicitly declared to carry, or not to carry, a
sign by using the keywords signed or unsigned
...


213


For some time, type unsigned char has been available
...




The void type has been available in most implementations for some years
...
At the same time, explicit rules are enacted against mixing
pointers and integers, and pointers of different type, without the use of casts
...
h> and ...




Enumerations are new since the first edition of this book
...
A
...
2)
...




The `usual arithmetic conversions'
`
'are changed, essentially from `for integers,
`
unsigned always wins; for floating point, always use double' `promote to the
'to `
smallest capacious-enough type
...
A
...
5
...
Also, assignment operators are
now single tokens; in the first edition, they were pairs, and could be separated by
white space
...




A unary + operator is introduced for symmetry with unary -
...
See Par
...
7
...
2
...




Applying the address-of operator to arrays is permitted, and the result is a pointer to
the array
...
The Standard makes its type explicitly
implementation-dependent, but requires the type, size_t, to be defined in a standard
header ( ...
A similar change occurs in the type (ptrdiff_t) of the
difference between pointers
...
A
...
4
...
A
...
7
...




The type of a shift expression is that of the left operand; the right operand can'
t
promote the result
...
A
...
8
...
A
...
7
...

See Pars
...
7
...
2, A
...
6
...
7
...



Empty declarations, which have no declarators and don' declare at least a structure,
t
union, or enumeration, are forbidden by the Standard
...




External data declarations without any specifiers or qualifiers (just a naked declarator)
are forbidden
...
The Standard makes it clear that
the scope of such a declaration is just the block
...




The name spaces of identifiers are somewhat different
...
A
...
1
...
(This has been common practice from some time
...




Automatic structures, unions, and arrays may be initialized, albeit in a restricted way
...




The controlling expression, and the case labels, of a switch may have any integral
type
Title: lets C
Description: Basics of C language and its brief concepts.