Ira Pohl is a Professor of Computer Science at the University of California, Santa Cruz and holds a Ph.D. in Computer Science from Stanford University. His research interests include artificial intelligence, the C and C++ programming languages, practical complexity problems, heuristic search methods, deductive algorithms, and educational and social issues. He originated error analysis in heuristic search methods and deductive algorithms.
Professor Pohl was formerly a Mackay professor at University of California- Berkeley and a ZWO fellow in the Netherlands. He is the author or co-author of Object-Oriented Programming Using C++, C++ Distilled: A Concise Ansi/Iso Reference and Style Guide, C by Dissection: The Essentials of C Programming, A Book on C: Programming in C, C++ for C Programmers, C++ for Fortran Programmers, C++ for Pascal Programmers, and Turbo C: The Essentials of C Programming, all published by Addison-Wesley.
Written by best-selling authors Al Kelley and Ira Pohl, A Book on C is a comprehensive tutorial and reference to C based on the ANSI C standard.
The C language is demonstrated with numerous examples and extensive exercises that guide readers through each concept. Step-by-step "dissections" of program code reveal the underlying logic of the programs and include in-depth implementation details. Features in this edition include: a chapter on moving from C to Java; more programming examples; new and improved dissections; more thorough coverage of multifile programming, pointers, and recursion; and an expanded appendix of standard library functions. In addition, there is more emphasis on Abstract Data Types, which provides the reader with a foundation for working with objects and facilitates programming in the problem domain.
(Each chapter concludes with a Summary and Exercises.)
Starting from Zero.
ANSI C Standard.
From C to C++.
From C and C++ to Java.
Programming and Preparation.
Variables, Expressions, and Assignment.
The Use of #define and #include.
The Use of printf() and scanf().
Flow of Control.
Arrays, Strings, and Pointers.
Operating System Considerations.
Writing and Running a C Program.
Interrupting a Program.
Typing an End-of-file Signal.
Redirection of the Input and the Output.
Characters and Lexical Elements.
Operators and Punctuators.
Precedence and Associativity of Operators.
Increment and Decrement Operators.
An Example: Computing Powers of 2.
The C System.
The Standard Library.
Declarations, Expressions, and Assignment.
The Fundamental Data Types.
Characters and the Data Type char.
The Data Type int.
The Integral Types short, long, and unsigned.
The Floating Types.
The Use of typedef.
The sizeof Operator.
The Use of getchar() and putchar().
The Use of abs() and fabs().
UNIX and the Mathematics Library.
Conversions and Casts.
The Integral Promotions.
The Usual Arithmetic Conversions.
Hexadecimal and Octal Constants.
Relational, Equality, and Logical Operators.
Relational Operators and Expressions.
Equality Operators and Expressions.
Logical Operators and Expressions.
The Compound Statement.
The Expression and Empty Statement.
The if and the if-else Statements.
The while Statement.
The for Statement.
An Example: Boolean Variables.
The Comma Operator.
The do Statement.
An Example: Fibonacci Numbers.
The goto Statement.
The break and continue Statements.
The switch Statement.
The Conditional Operator.
The return Statement.
Function Prototypes in C++.
An Example: Creating a Table of Powers.
Function Declarations from the Compiler’s Viewpoint.
An Alternate Style for Function Definition Order.
Function Invocation and Call-by-Value.
Developing a Large Program.
What Constitutes a Large Program?
Parallel and Nested Blocks.
Using a Block for Debugging.
The Storage Class auto.
The Storage Class extern.
The Storage Class register.
The Storage Class static.
Static External Variables.
An Example: The Towers of Hanoi.
The Relationship Between Arrays and Pointers.
Pointer Arithmetic and Element Size.
Arrays as Function Arguments.
An Example: Bubble Sort.
Dynamic Memory Allocation With calloc() and malloc().
Offsetting the Pointer.
An Example: Merge and Merge Sort.
String-Handling Functions in the Standard Library.
The Storage Mapping Function.
Formal Parameter Declarations.
The Use of typedef.
Arrays of Pointers.
Arguments to main().
Functions as Arguments.
Functions as Formal Parameters in Function Prototypes.
An Example: Using Bisection to Find the Root of a Function.
The Kepler Equation.
Arrays of Pointers to Function.
The Type Qualifiers const and volatile.
Bitwise Operators and Expressions.
Bitwise Binary Logical Operators.
Left and Right Shift Operators.
Software Tools: Printing an int Bitwise.
Packing and Unpacking.
Multibyte Character Constants.
An Example: The Game of Paper, Rock, Scissors.
The Use of #include.
The Use of #define.
Macros with Arguments.
The Type Definitions and Macros in stddef.h.
An Example: Sorting with qsort().
An Example: Macros with Arguments.
The Macros in stdio.h and ctype.h.
The Predefined Macros.
The Operators # and ##.
The assert() Macro.
The Use of #error and #pragma.
An Example: Quicksort.
Accessing Members of a Structure.
Operator Precedence and Associativity: A Final Look.
Using Structures with Functions.
Initialization of Structures.
An Example: Playing Poker.
An Example: Accessing Bits and Bytes.
The ADT Stack.
Linear Linked Lists.
Some List Processing Functions.
An Example: Polish Notation and Stack Evaluation.
Binary Tree Traversal.
General Linked Lists.
The Use of calloc() and Building Trees.
The Output Function printf().
The Input Function scanf().
The Functions fprintf(), fscanf(), sprintf(), and sscanf().
The Functions fopen() and fclose().
An Example: Double Spacing a File.
Using Temporary Files and Graceful Functions.
Accessing a File Randomly.
File Descriptor Input/Output.
File Access Permissions.
Executing Commands from Within a C Program.
Using Pipes from Within a C Program.
The C Compiler.
Using the Profiler.
How to Time C Code.
The Use of make.
The Use of touch.
Other Useful Tools.
Creating a Concurrent Process with fork().
Overlaying a Process: the exec...() Family.
Using the spawn...() Family.
Interprocess Communication Using pipe().
An Example: The Dining Philosophers.
Dynamic Allocation of Matrices.
Why Arrays of Arrays Are Inadequate.
Building Matrices with Arrays of Pointers.
Adjusting the Subscript Range.
Allocating All the Memory at Once.
Returning the Status.
Classes and Abstract Data Types.
Constructors and Destructors.
Object-oriented Programming and Inheritance.
Benefits of Object-oriented Programming.
Variables and Types.
Classes and Abstract Data Types.
Construction and Destruction of Class Types.
Object-oriented Programming and Inheritance.
Polymorphism and Overriding Methods.
Benefits of Java and OOP.
Testing a Character.
Mapping a Character.
Opening, Closing, and Conditioning a File.
Accessing the File Position Indicator.
Removing or Renaming a File.
A.13 General Utilities.
Dynamic Allocation of Memory.
Searching and Sorting.
Pseudo Random-Number Generator.
Communicating with the Environment.
Multibyte Character Functions.
Multibyte String Functions.
Leaving the Program.
Memory and String Handling.
Date and Time.
Accessing the Clock.
Accessing the Time.
Using File Descriptors.
Creating a Concurrent Process.
Overlaying a Process.
Suspending Program Execution.
Structures and Unions.
A Book on C conveys an appreciation for both the elegant simplicity and the power of this general-purpose programming language. By presenting interactive running programs from many application areas, this book describes the ANSI version of the C language. The complete language is presented in a step-by-step manner, along with many complete working programs.
Where appropriate, we discuss the differences between traditional C and ANSI C. (Traditional C still remains in wide use.) Dozens of example programs are available to illustrate each important language feature, and many tables summarize key information and provide easy access for later reference. Each chapter ends with a summary and exercises. The summary reviews key elements presented in the chapter, and the exercises augment and extend the text.
This book assumes a general-purpose knowledge of the C language. It is intended for use in either a first or second programming course. However, it can be readily used in conjunction with courses on topics such as comparative programming languages, computational linguistics, data structures, database systems, fractal geometry, graphics, numerical analysis, operating systems, programming methodology, and scientific applications. C is suitable for applications from each of these domains, and all features of C needed to code such applications are explained. This book is appropriate for a data structures course because advanced data structuring features such as enumeration types, unions, self-referential structures, and ragged arrays are discussed. For operating systems courses concerned with UNIX or Windows 95/NT, the book explores the file structure and systems routines that enable the C programmer to add to existing systems libraries and understand the C code underlying the operating system. For applications programming and scientific programming, there is discussion of how to write sample function libraries. Statistics, root finding, sorting, text manipulation, file handling, and game playing are all represented with working code.
New Java Section. In Chapter 14, "Moving from C to Java," we discuss how the C programmer can very naturally and easily begin programming in Java, a language of interest for work on the Internet. The Java programming language borrows ideas from both C and C++ and is designed to run in a machine- and system-independent manner. This makes it suitable for Internet work, such as writing applets for Web pages that get used by browsers. Because Java is an extension of C and C++, it is readily learned by the C programmer.
Complete ANSI C Language. Computer professionals will have access to a complete treatment of the language, including enumeration types, list processing, and the operating system interface. Chapter 1, "An Overview of C," presents an overview of the language. After reading this chapter, the professional will already be able to write C code. Since the chapters are self-contained, the knowledgeable reader can skip to particular sections as needed. Chapter 11, "Input/Output and the Operating System," gives a thorough introduction to the connections to the operating system. This information will benefit the professional systems programmer needing to use C to work within an MS-DOS or UNIX environment.
Interactive Environment. This book is written entirely with the modern interactive environment in mind. Experimentation is encouraged throughout. Keyboard and screen input/output is taken as the norm, and its attendant concerns are explained. Thus, the book is appropriate for users of small home and business computers as well as to users of large interactive systems. We assume that the reader will have access to an interactive ANSI C system. During the writing of this book, we used a number of different C systems: various Borland and Microsoft compilers running on IBM-compatible Pentium machines, the GNU gcc compiler and native compilers running on various workstations from DEC, SGI, and Sun, and the C compiler that runs on the Cray supercomputer in San Diego.
Working Code. Our approach to describing the language is to use examples, explanation, and syntax. Working code is employed throughout. Small but useful examples are provided to describe important technical points. Small because small is comprehensible. Useful because programming is based on a hierarchy of building blocks and ultimately is pragmatic. The programs and functions described in the book can be used in actual systems. The authors' philosophy is that one should experiment and enjoy.
Dissections. We use highlighted "dissections" on many programs and functions throughout the book. Dissection is a unique pedagogical tool first developed by the authors in 1984 to illuminate key features of working code. A dissection is similar to a structured walk-through of the code. Its intention is to explain to the reader newly encountered programming elements and idioms found in working code.
Flexible Organization. This book is constructed to be very flexible in its use. Chapter 1, "An Overview of C," is in two parts. The first part explains the crucial programming techniques needed for interactive input/output, material that must be understood by all. The second part of Chapter 1 goes on to survey the entire language and will be comprehensible to experienced programmers familiar with comparable features from other languages. This second part can be postponed in a first programming course. Caution: Beginning programmers should postpone the second part of Chapter 1.
Chapter 2, "Lexical Elements, Operators, and the C System," describes the lexical level of the language and syntactic rules, which are selectively employed to illustrate C language constructs. The instructor may decide to teach Backus-Naur-Form (BNF) notation as described in Chapter 2 or may omit it without any loss of continuity. The book uses BNF style syntactic descriptions so that the student can learn this standard form of programming language description. In addition, language components are thoroughly described by example and ordinary explanation.
Reference Work. This book is designed to be a valuable reference to the C language. Throughout the book, many tables concisely illustrate key areas of the language. The complete ANSI C standard library, along with its associated header files, is described in the Appendix A, "The Standard Library." Sections in the appendix are devoted to explaining each of the standard header files such as ctype.h, stdio.h, and string.h. Where appropriate, example code is given to illustrate the use of a particular construct or function.
In Appendix B, "Language Syntax," we provide the complete syntax of the C language. In Appendix C, "ANSI C Compared to Traditional C," we list the major differences between ANSI C and traditional C. Finally, special care has been taken to make the index easy to use and suitable for a reference work.
The Complete ANSI C Language. Chapters 3 through 10 cover the C language feature by feature. Many advanced topics are discussed that may be omitted on first reading without loss of comprehension, if so desired. For example, enumeration types are relatively new to the language, and their use can be omitted in a first course. Machine-dependent features such as word size considerations and floating-point representation are emphasized, but many of the details need not concern the beginner.
The Preprocessor. Chapter 8, "The Preprocessor," is devoted entirely to the preprocessor, which is used to extend the power and notation of the C language. Macros can be used to generate inline code that takes the place of a function call. Their use can reduce program execution time. The chapter presents a detailed discussion of the preprocessor, including new features added by the ANSI committee. In traditional C, the preprocessor varies considerably from one compiler to another. In ANSI C, the functionality of the preprocessor has been completely specified.
Recursion and List Processing. Chapter 5, "Functions," has a careful discussion of recursion, which is often a mystifying topic for the beginner. The use of recursion is illustrated again in Chapter 8, "The Preprocessor," with the quicksort algorithm and in Chapter 10, "Structures and List Processing," with basic list processing techniques. A thorough knowledge of list processing techniques is necessary in advanced programming and data structure courses.
Operating System Connection. Chapter 11, "Input/Output and the Operating System," makes the operating system connection. In this chapter, we explain how to do file processing and discuss at length the various input/output functions in the standard library. We also explain how to execute a system command from within a C program and how to set file permissions and use of environment variables. We give explicit examples showing the use of the profiler, the librarian, and the make facility.
Advanced Applications. We discuss a number of advanced applications in Chapter 12, "Advanced Applications." We present topics such as creating concurrent processes, overlaying a process, interprocess communication, and signals, along with working code. Also, we discuss the dynamic allocation of vectors and matrices for engineers and scientists. These advanced topics can be used selectively according to the needs of the audience. They could form the basis for an excellent second course in programming practice. This book can be used, too, as an auxiliary text in advanced computer science courses that employ C as their implementation language.
Tables, Summaries, and Exercises. Throughout the book are many tables and lists that succinctly summarize key ideas. These tables aid and test language comprehension. For example, C is very rich in operators and allows almost any useful combination of operator mix. It is essential to understand order of evaluation and association of each of these operators separately and in combination. These points are illustrated in tables throughout the text. As a reference tool, the tables and code are easily looked up.
The exercises test elementary features of the language and discuss advanced and system-dependent features. Many exercises are oriented to problem solving, others test the reader's syntactic or semantic understanding of C. Some exercises include a tutorial discussion that is tangential to the text but may be of special interest to certain readers. The exercises offer the instructor all levels of question, so as to allow assignments suitable to the audience.
Our special thanks go to Debra Dolsberry, who acted as the chief technical editor for this book. She was largely responsible for using FrameMaker to create PostScript files suitable for the typesetting of this book. Our special thanks also go to Robert Field, ParcPlace Systems, Mountain View, California, who acted as the chief technical reviewer for the first edition of this book. We found his expertise and suggestions extremely valuable. The ''Tower of Hanoi'' picture in Chapter 5, "Functions," and the "Dining Philosophers" picture in Chapter 10, "Structures and List Processing," are due to John de Pillis, University of California, Riverside. Our special thanks go to him, too.We also want to thank other people who provided us with helpful suggestions: Murray Baumgarten, University of California, Santa Cruz; Michael Beeson, San Jose State University, San Jose, California; Randolph Bentson, Colorado State University, Ft. Collins; Jim Bloom, University of California, Berkeley; John Bowie, Hewlett-Packard Co., Inc.; Skona Brittain, University of California, Santa Barbara; Timothy Budd, University of Arizona, Tucson; Nick Burgoyne, University of California, Santa Cruz; Jim Chrislock, Mindcraft, Inc.; Al Conrad, University of California, Santa Cruz; Jeff Donnelly, University of Illinois, Urbana; Dick Fritz, AT&T Bell Laboratories; Rex Gantenbein, University of Wyoming, Laramie; Harry Gaver, SRI International, Georgia; Leonard Garrett, Temple University, Philadelphia; William Giles, San Jose State University, San Jose, California; Susan Graham, University of California, Berkeley; Jorge Hankamer, University of California, Santa Cruz; Robert Haxo, Auspex, Inc., San Jose, California; Mike Johnson, Oregon State University, Corvallis; Keith Jolly, Chabot College, San Leandro, California; Carole Kelley, Cabrillo College, Aptos, California; Clifford Layton, Rogers State University; Darrell Long, University of California, Santa Cruz; Charlie McDowell, University of California, Santa Cruz; Andrew Pleszkun, University of Colorado, Boulder; Geoffrey Pullum, University of California, Santa Cruz; Peter Rosencrantz, The Santa Cruz Operation, Inc.; Mike Schoonover, HewlettPackard Co., Inc.; Peter Scott, University of California, Santa Cruz; Alan Shaw, University of Washington, Seattle; Tilly Shaw, University of California, Santa Cruz; Matt Stallmann, University of Denver.
In addition, we would like to thank our sponsoring editor Carter Shanklin for his enthusiasm, support, and encouragement; and we would like to thank John Fuller for his careful attention to the production of this book on C.