Using QuickC PDF
Using QuickC PDF
Werner
Feibel
L
i
Using QuickC
®
Using QuickC
Werner Feibel
Osborne McGraw-Hill
Berkeley, California
Osborne McGraw-Hill
2600 Tenth Street
Berkeley, California 94710
U.S.A.
For information on translations and book distributors outside of the U.S.A., write to
Osborne McGraw-Hill at the above address.
A complete list of trademarks appears on page 595.
Using QuickC®
Copyright © 1988 by McGraw-Hill, Inc. All rights reserved. Printed in the United States of
America. Except as permitted under the Copyright Act of 1976, no part of this publication
information has been obtained by Osborne McGr«w-Hill from sources believed to be reliable. However,
because of the possibility of human or mechanical error by our sources. Osborne McGraw-Hill, or others, Osborne
IVIcCraw-Hill does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible
for any errors or omissions or the results obtained from use of such information.
For my parents, with love and thanks
for all they've done for me
J
Contents
Introduction xiii
Introducing C 1
C Features 2
An Example of C Programming 3
The Nature of C 5
Using C 7
Why QuickC U
6 Controlling C 167
Relational and Equality Operators 168
Logical Operators 170
The if-else Construct 172
The switch Statement 178
More Operators 182
Loops in C 186
Components of the while Loop 188
The do-while Loop 191
The for Loop 193
break and continue 201
Summary 204
7 Functioning in C 205
C Functions 206
Flow of Control 207
Function Returns 213
Formal and Actual Parameters 217
Summary 225
10 Pointers 263
Objects, Lvalues, Values 264
Pointers 267
Pointers as Function Parameters 274
Pointer Arithmetic 280
Miscellaneous Points 284
Pointer Pitfalls 285
Summary 287
Index 597
Acknowledgments
Many people deserve thanks for making this book possible. The following
people were particularly helpful and encouraging throughout the project.
Kris Jamsa deserves thanks for his technical review and very helpful
suggestions. Many of the book's good features are there because of his
suggestions and corrections; the book's defects are there because I didn't listen
to Kris's objections.
I also wish to thank the people at Osborne/ McGraw-Hill who are always
helpful, friendly, and accommodating; it has been a pleasure to work with
them. Jeff Pepper deserves special thanks for getting this project started and
for keeping it on the smoothest course and Lyn Cordell
possible. Liz Fisher
helped keep me on course, and dealt gracefully and efficiently with ambiguous
materials and last minute changes, for which I thank them. Thanks also to the
unsung heroes in the art and production departments at Osborne/ McGraw-
Hill. They had to work extra hard (on a tight schedule made even tighter by
changes required late in the production process) to turn the manuscript into a
real book.
owe my friends many thanks for putting up with me and keeping
Finally, I
me going during the past few months. In particular, I want to thank Luanne
Panarotti, Scott Barnes, Alexa Beiser, Dan Kiely, and little Dylan Reiser
Kiely, whose favorite part of the project was the printer cable.
This book may have gotten done without these people, but it would have
been a lot less fun.
Introduction
xlll
xiv Using QuickC
ming environment. In later chapters, youll find sections that illustrate how to
use various QuickC features as part of the discussion of particular C con-
structs. I've also included advice on some pitfalls you may encounter when
language definition currently being drafted, so you can also use this book to
learn C with other compilers.
The text contains lots of examples, since these usually illustrate a point
better than several paragraphs of description. Youll also find suggested modi-
ficationsand variations to try. The programs are designed to let you experi-
ment easily, and many of them will report on their own actions.
The best way to learn a programming language is to use it. Whether your
main interest is in C or QuickC, you'll get a lot more out of this book and —
enjoy it much more — if you enter the programs and examples and try them
out yourself Once you've done that, experiment with the examples; change
some of the functions or the input. One of the best ways to deepen your
understanding of a language is to experiment with it. Then, once you feel
comfortable with the material covered here, work on projects that interest you.
You'll find it is helpful, though not essential, to have some familiarity with
programming — perhaps with a language such as Pascal or BASIC. If you
have used either or both of these languages, you'll find that C differs in
important, and sometimes in very subtle, ways. If you have no programming
experience, don't worry. You'll still be able to use this book, but you may need
to put in some extra effort to be sure you understand some of the terms and
concepts.
The complete source code for all the programs is included here, so you can
simply type them in from the book. However, if you want to save yourself the
demands of that task, the source code for all the programs in this book (as well
as some additional programs and functions) can be purchased on two 360K
diskettes, for $22 ($20 plus $2 for postage and handling). The diskettes contain
about 450K of source files. In addition to the programs from the book, these
files include a quick and dirty program for testing functions during develop-
ment, a simple daily reminder program that you can tailor to your needs, and
several others.
To order the diskette, use the form that follows this introduction.
To order the source code diskettes for Using QuickC, please provide the
following information and a check or money order for the appropriate
amount:
$25 per copy ($20 + $5 shipping and handling) for foreign orders
$23 per copy ($20 + $2 shipping and handling + $ sales tax) for Massachu-
1
setts residents
$22 per copy ($20 + $2 shipping and handling) for other orders
Name
Street Address
Please send this information, along with your check or money order to:
Werner Feibel
P.O. Box 2499
Cambridge, MA 02238
Osborne/ McGraw-Hill assumes no responsibility for this offer. This is solely
the offer of Werner Feibel, and not of Osborne/ McGraw-Hill.
I
A
1
Introducing C
of C; learning how to use the language to its fullest is your real challenge. Your
rewards, which include programming power and a better understanding of
your computer, are definitely worth the effort.
Microsoft Corporation's QuickC makes C
and accessible by
available
providing a complete, easy-to-use language implementation. QuickC is an
enhanced compiler (it converts programs into object code), a linker (it pro-
duces executable files), a shell (it serves as a command interpreter), and a rich
programming environment. With the help of this book, you'll be able to take
advantage of QuickC's special features, and make C work for you.
C Features
Performance Features
C is smaller than Pascal, Modula-2, or even BASIC. C has only about 30
keywords or reserved words. Because many of C's actions are close to
assembly-level activity, using C can increase the speed of your program and
make it easier to create concise, "optimized" expressions.
Introducing C
C gives you a complete set of tools. It's your job to maximize its potential.
Because C lets you get very close to the actual memory cells and registers in
your computer, you can do just about anything in a C program. This capability
makes C very powerful — ideal for complex projects, or programs that need to
take full advantage of the system on which they are running.
Portability
C can be very portable. One reason for C's portability is the preprocessor,
which makes it possible to substitute information specific to a particular
machine when compiling or running a program. As you'll see in later chapters,
you can use the preprocessor to help make your programs run faster.
IVIodularity
One feature that helps make C portable is its capacity to build programs out of
small functions and library modules that have already been compiled. The
library modules can contain C functions specific to a particular machine.
Because you can build and compile independent function libraries. C allows
you to write programs in a modular fashion. You can break large programs
into smaller units, which contain functions that can be used together in other
An Example of C Programming
The following listing shows one way of incorporating information from other
files into a program, and illustrates one way of increasing program portability.
Using QuickC
feed, which puts the cursor at the leftmost column of the next line.
The % begins a placeholder for a particular type of information, whose
value is substituted when printf( ) writes the material; the s indicates that a
string is to be written. In our example, %s is the placeholder for PROG
MESSAGE, which contains a string. In C, a string is a sequence of characters
terminated by a special character, which we'll discuss later.
enclosed in braces.
Within the body of the function, individual statements end with a semi-
colon. Comments may appear anywhere in a program, and are enclosed
between /* and */.
Note that PROG MESSAGE is not defined anywhere in the program
file. Rather, this value is specified in the header file, proginfo.h, which the
compiler reads when processing the file containing the main program. Such
header files are common
Each system or program may have its own
in C.
header files. These files contain program or operating system specific values
and definitions. For example, when running under QuickC, the program's
Introducing C
message would read "QuickC Version 1.0"; running under Microsoft C Ver-
sion 5.0, the message might be "Microsoft C Version 5.0. "These messages are
stored in a file such as proginfo.h.
Most C compilers provide a file called stdio.h. which contains system-and
implementation-specific information, and which associates specific values,
such as "QuickC Version 1.0" with names, such as PROG MESSAGE.
Search your QuickC directories for files with the extension .h. These are the
header files provided with your compiler.
The Nature of C
C can be described as a middle-level language, having characteristics and
capabilities of both high- and low-level languages. This is one reason for its
and Brian Kernighan, who was involved in much of the early work with C,
intended C to be useful for writing systems (such as operating systems) as well
as application programs (such as editors). Therefore, the developers gave C the
speed and flexibility of assembly language, but the data structures and control
constructs (such as if-then, for, while) of high-level languages.
Table 1-1 lists some properties of high- and low-level languages, and
indicates where C stands with respect to these properties. Note that C has
almost every property listed.
A Small Language
C has a very small vocabulary — only about 30 keywords. Although the words
are few, you can say a great deal with them. A small vocabulary does not mean
Using QuickC
a weak language: some linguists claim that fewer than 900 words are needed
to communicate effectively in English.
On the other hand, C has lots of operators or symbols that cause specific
actions. In fact, C has more operators than keywords! This combination of a
small vocabulary and many operators lets you use C as a "construction set."
You can easily create individual statements or functions to do just the right
amount of work. As you'll see, C programs are usually built of small functions
that perform specific tasks. These functions are collected in modules and used
as needed.
The Power of C
Despite its smallC is being used for a huge range of programs. Large parts
size,
of the powerful UNIX and DOS operating systems are written in C. Similarly,
C has been used to write compilers (including C compilers), editors, typeset-
tingprograms (such as troff and TeX), and such programs as dBaselll and
Microsoft Windows.
At the other end of the spectrum, you will find many C programs that
perform specific tasks, such as display a calendar for any month or year, count
thenumber of words in a file, list the contents of a directory, find a particular
word or other expression in specified files, compute the interest payments on a
loan under various conditions, and so on. Source code for many of these
Introducing C
Standard Versions
There is as yet no official standard for C. Although C is used everywhere, it is
only now being officially defined. There has been a de facto standard version
of the language, summarized in The C Programming Language by Brian
Kernighan and Dennis Ritchie (Englewood Cliffs, New Jersey:
Prentice-Hall, 1978). This version of C is known as "K&R C," with compilers
often claiming that they implement "full K&R C," or "K&R C, with exten-
sions."
After several years, however, a standards committee is about to complete
its work on an official definition of the language. The working name for this
version is "Draft Proposed ANSI Standard C." Eventually, C's official name
will be "ANSI Standard C." (ANSI stands for American National Standards
Institute.)
Using C
Getting a C program from idea to completion takes several steps, with each
step modifying or extending your program. In the next chapter you'll learn
how to write C
programs and get them to run using QuickC. This section
summarizes the main components of a C program and the major tasks
involved in getting from your text file to a running program. We'll see that
QuickC puts the tools for accomplishing various tasks under one program
Using QuickC
"shell." This makes it easy to move from one phase of the program creation
process to another.
When you create a C program, various types of files are created and used.
These include: source and header files created with a text editor; library and
other object files, linked with the compiled version of your main program file;
and an executable file that runs the program.
The first step is to create the program in text form — this is the source file.
The file contains the main program, niain( ), which calls printf( ), as did
our first example. There is also an instruction (#include "proginfo.h") to read
the contents of a header file, proginfo.h.
There are several new features. Notice that this program also writes
numerical information, the value of variable il. The %d (for decimal) place-
holder indicates this fact. In the second call to printf( ), the value to be
substituted is the value of il, which is 16 after the addition is carried out.
The second argument, information passed to printf(), is substituted for
the placeholder in the function's first argument. This simple replacement
strategy extends to handle additional arguments, as you'll soon see.
The program also illustrates how to define a variable in C, that is, how to
associate a data type with a variable name. (If you're not used to working with
data types, and are not sure what they are, don't worry. Data types are
explained in Chapter 3.) The variable il is defined to be of type int, for integer.
Introducing C
assigns the result of adding 7 and 9 to the variable il. You'll learn about
variable definition and assignments in Chapter 3.
Header files are ordinary text files either written by you or provided with
the compiler. These files generally contain information needed for specific
tasks on a particular machine or with a particular compiler. Associated with
this information are mnemonic names, which are easier to remember than
obscure numerical values. When you use these names, the compiler substitutes
the values it finds for each name in the header files. For example, the header
file, proginfo.h, may contain the following:
The second statement provides a name for the largest integer represented
on the system. This name is much more meaningful than the actual number,
which may vary from machine to machine. When the compiler sees MAX
INT in the source file, it substitutes the value 32767. In the third instance, the
compiler substitutes the numerical value when you use false in your program.
(Later, you will see how C represents true and false.)
Such substitutions work out well for you and your program. You can use
.
10 Using QuickC
with function library files and other precompiled (object) files. The outcome of
this linking process is the program itself often known as an executable file.
Library Files
1 Source files created with an editor and processed by the compiler. One
of these files contains the main program function, main( ). Every C
program must have at least one source file.
2. Optional header files, which may contain various values and defini-
tions for the program or the environment.
3. Library files and other object files, which are linked with your com-
Introducing C 11
4. An executable file.
^REMEMBER
• There must be at least one source file — otherwise you have nothing to
compile or run.
All files other than source files — headers, libraries, and so forth — are
optional.Whether you need such files, and how you add them, depends on the
C compiler you are using and the tasks you are trying to accomplish in your
program.
If all goes well, and the compilation and linking processes take place
without error, your program will be ready to run. Of course, that's often when
the real fun begins, when you discover the surprising things you've uninten-
tionally instructed your program to do.
3. Linking the resulting object file with whatever libraries and additional
modules are needed
Why QuickC?
QuickC makes it easy to carry out the steps required for C programming in a
flexible manner, within a tightly integrated and powerful environment. The
QuickC system provides a shell within which you can easily move from one
12 Using QuickC
QuickC to optimize the program for speed (at program size); or you
the cost of
can ask it to warn you about any questionable programming practices, such as
constructs that violate the official language definition.
If you are used to writing programs, you know the tedium involved in
fixing small errors as the compiler encounters them. You must stop the
compilation, call up your editor, change your file, save it, call up the compiler,
keystrokes. If there are any problems with the program, QuickC puts you back
You can edit the file, then tell QuickC
in the source file at the appropriate place.
to continue. The system then recompiles, relinks, and reruns the revised
program.
QuickC's integrated environment is also convenient for debugging. You
can trace the program's execution using the debugging facility. If a change is
will get the system to reprocess your program and run it again, but this time in
debugging mode.
QuickC comes "preloaded" with many functions defined in separate
libraries by other C implementations. This gives you access to a more powerful
C without forcing you to link in separate libraries to get this power.
QuickC does its work quickly. In the next chapter, we will look
Best of all,
at the QuickC environment and explore it with a few sample programs.
Throughout the book, you will learn ways of taking particular advantage of
QuickC's environment.
A Quick Look
at QuickC
13
14 Using QuickC