Home > Store > Programming > C/C++

C Programming FAQs: Frequently Asked Questions

Register your product to gain access to bonus material or receive a coupon.

C Programming FAQs: Frequently Asked Questions


  • Your Price: $27.99
  • List Price: $34.99
  • Usually ships in 24 hours.


  • Copyright 1996
  • Dimensions: 6-1/4x9-1/4
  • Pages: 432
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-84519-9
  • ISBN-13: 978-0-201-84519-8

Summit furnishes you with answers to some of the most frequently asked questions in C. Extensively revised from his popular FAQ list on the Internet, more than 400 questions are answered to illustrate key points and to provide practical guidelines for programmers. C Programming FAQs is a welcomed reference for all C programmers, providing accurate answers, insightful explanations, and clarification of fine points along with numerous code examples.

  • How-to-manual covering the C language in a practical, nuts-and-bolts way
  • Concise answers to more than 400 most frequently asked questions with definitively correct answers
  • Description of real problems that crop up when writing actual programs
  • Clarification of widely misunderstood issues: subtle portability problems, proper language usage, system-specific issues.



Source Code

Program code to accompany text is available at our ftp site archived in PC-, Macintosh-, and Unix-familiar formats. Files are identical except for the method used in compressing/archiving.

cfaq.zip (55,225 bytes) contains the files, compressed and archived in PKZIP format (binary). Currently, we recommend using the freeware utility Unzip by Info-Zip to extract .zip files. We suggest you download it directly from Info-Zip and take a look at the other information on their web page. You may also download Unzip for DOS via ftp from our pub/tools/win directory.

If you do already have PKUNZIP 2.04g, remember to use the -d option when pkunzipping or you will lose the directory structure [for those supplements which contain multiple directories], and all files will be written to the same directory, overwriting some, disorganizing many:

    pkunzip -d cfaq.zip

cfaq.sit.hqx (124,929 bytes) contains the files in stuffed binhex format (ASCII) for the Macintosh platform. These files may be extracted using StuffIt Expander, available either from Aladdin or via ftp from our pub/tools directory.

cfaq.tar.z (42,198 bytes) contains the files in Unix tarred/compressed format (binary). To uncompress and detar under Unix, the following command sequence can be used:

   uncompress cfaq.tar   tar -xvf cfaq.tar

Utilities such as GZip may also be used to uncompress the files.

An Errata list for the first printing is available as a text file via ftp.

Sample Content

Table of Contents

1. Declarations and Initializations.

Basic Types.

Pointer Declarations.

Declaration Style.

Storage Classes.


The const Qualifier.

Complex Declarations.

Array Sizes.

Declaration Problems.



2. Structures, Unions, and Enumerations.

Structure Declarations.

Structure Operations.

Structure Padding.

Accessing Members.

Miscellaneous Structure Questions.




3. Expressions.

Evaluation Order.

Other Expression Questions.

Preserving Rules.

4. Pointers.

Basic Pointer Use.

Pointer Manipulations.

Pointers as Function Parameters.

Miscellaneous Pointer Use.

5. Null Pointers.

Null Pointers and Null Pointer Constants.

The NULL Macro.


What's Really at Address 0?

6. Arrays and Pointers.

Basic Relationship of Arrays and Pointers.

Arrays Can't Be Assigned.


Pointers to Arrays.

Dynamic Array Allocation.

How can I avoid fixed-sized arrays?

Functions and Multidimensional Arrays.

Sizes of Arrays.

7. Memory Allocation.

Basic Allocation Problems.

Calling malloc.

malloc Problems.

Freeing Memory.

Sizes of malloc'ed Blocks.

Other Allocation Functions.

8. Characters and Strings.

9. Boolean Expressions and Variables.

10. C Preprocessor.

Macro Definitions.

Header Files.

Conditional Compilation.

Fancier Processing.

Macros with Variable-Length Argument Lists.

11. ANSI/ISO Standard C.

The Standard Itself.

Function Prototypes.

The const Qualifier.

Using main().

Preprocessor Features.

Other ANSI C Issues.

Old or Non-Standard Compilers.


12. Stdio.

printf Formats.

scanf Formats.

scanf Problems.

Other stdio Function.

Opening and Manipulating Files.

Redirecting stdin and stdout.

"Binary" I/O.

13. Library Functions.

13 String Functions.


Date and Time.

Random Numbers.

Other Library Functions.

14. Floating Point.

15. Variable-Length Argument Lists.

Calling Varargs Functions.

Implementing Varargs Functions.

Extracting Variable-Length Arguments.

Harder Problems.

16. Strange Problems.

17. Style.

18. Tools and Resources.




19. System Dependencies.

Keyboard and Screen I/O.

Other I/O.

Files and Directories.

Accessing Raw Memory.

"System" Commands.

Process Environment.

Other System-Dependent Operations.


20. Miscellaneous.

Miscellaneous Techniques.

Bits and Bytes.


Switch Statements.

Miscellaneous Language Features.

Other Languages.


Trivia. 0201845199T04062001



At some point in 1979, I heard a lot of people talking about this relatively new language, C, and the book which had just come out about it. I bought a copy of K&R, otherwise known as The C Programming Language, by Brian Kernighan and Dennis Ritchie, but it sat on my shelf for a while because I didn't have an immediate need for it (besides which I was busy being a college freshman at the time). It proved in the end to be an auspicious purchase, though, because when I finally did take it up, I never put it down: I've been programming in C ever since.

In 1983, I came across the Usenet newsgroup net.lang.c, which was (and its successor comp.lang.c still is) an excellent place to learn a lot more about C, and to find out what questions everyone else is having about C, and to discover that you may not know all there is to know about C after all. It seems that C, despite its apparent simplicity, has a number of decidedly non-obvious aspects, and certain questions come up over and over again. This book is a collection of some of those questions, with answers, based on the Frequently-Asked Questions ("FAQ") list which I began posting to comp.lang.c in May, 1990.

I hasten to add, however, that this book is not intended as a critique or "hatchet job" on the C language. It is all too easy to blame a language (or any tool) for the difficulties its users encounter with it, or to claim that a properly-designed tool "ought" to prevent its users from misusing it. It would therefore be easy to regard a book like this, with its long lists of misuses, as a litany of woes attempting to show that the language is hopelessly deficient. Nothing could be farther from the case.

I would never have learned enough about C to be able to write this book, and I would not be attempting to make C more pleasant for others to use by writing this book now, if I did not think that C was a great language or if I did not enjoy programming in it. I do like C, and one of the reasons that I teach classes in it and spend time participating in discussion about it on the Internet is that I would like to discover which aspects of C (or of programming in general) are difficult to learn or keep people from being able to program efficiently and effectively. This book represents some of what I've learned: these questions are certainly some of the ones people have the most trouble with, and the answers have been refined over a several-year period in an attempt to ensure that people don't have too much trouble with them.

A reader will certainly have trouble if there are any errors in these answers, and although the reviewers and I have worked hard to eliminate them, it can be as hard to eradicate the last error from a large manuscript as it is to stamp out the last bug in a program. I will appreciate any corrections or suggestions sent to me in care of the publisher or at the e-mail address below, and I would like to offer the customary $1.00 reward to the first finder of any error. If you have access to the Internet, you can check for an errata list (and a scorecard of the finders) at the ftp and http addresses mentioned in question 20.40.

As I hope I've made clear, this book is not a critique of the C Programming language, nor is it a critique of the book from which I first learned C, nor of that book's authors. I didn't just learn C from K&R; I also learned a lot about programming. As I contemplate my own contribution to the C programming literature, my only regret is that the present book does not live up to a nice observation made in the second edition of K&R, namely that "C is not a big language, and it is not well served by a big book." I hope that those who most deeply appreciate C's brevity and precision (and that of K&R) will not be too offended by the fact that this book says some things over and over and over, or in three slightly different ways.

Though my name is on the cover, there are a lot of people behind this book, and it's hard to know where to start handing out acknowledgments. In a sense, every one of comp.lang.c's readers (today estimated at 320,000) is a contributor: the FAQ list behind this book was written for comp.lang.c first, and this book retains the flavor of a good comp.lang.c discussion.

This book also retains, I hope, the philosophy of correct C programming which I began learning when I started reading net.lang.c. Therefore, I shall first acknowledge the posters who stand out in my mind as having most clearly and consistently articulated that philosophy: Doug Gwyn, Guy Harris, Karl Heuer, Henry Spencer, and Chris Torek. These gentlemen have displayed remarkable patience over the years, answering endless questions with generosity and wisdom. I was the one who stuck his neck out and started writing the Frequent questions down, but I would hate to give the impression that the answers are somehow mine. I was once the student (I believe it was Guy who answered my post asking essentially the present volume's question 5.10), and I owe a real debt to the masters who went before me. This book is theirs as much as mine, though I retain title to any inadequacies or mistakes I've made in the presentation.

The former on-line FAQ list grew by a factor of three in the process of becoming this book, and its growth was a bit rapid and awkward at times. Mark Brader, Vinit Carpenter, Stephen Clamage, Jutta Degener, Doug Gwyn, Karl Heuer, Joseph Kent, and George Leach read proposals or complete drafts and helped to exert some control over the process; I thank them for their many careful suggestions and corrections. Their efforts grew out of a shared wish to improve the overall understanding of C in the programming community. I appreciate their dedication.

Three of those reviewers have also been long-time contributors to the on-line FAQ list. I thank Jutta Degener and Karl Heuer for their help over the years, and I especially thank Mark Brader, who has been my most persistent critic ever since I first began posting the comp.lang.c FAQ list five years ago. I don't know how he has had the stamina to make as many suggestions and corrections as he has, and to overcome my continuing stubborn refusal to agree with some of them, even though (as I eventually understood) they really were improvements. You can thank Mark for the form of many of this book's explanations, and blame me for mangling any of them.

Additional assorted thanks: to Susan Cyr for the cover art; to Bob Dinse and Eskimo North for providing the network access which is particularly vital to a project like this; to Bob Holland for providing the computer on which I've done most of the writing; to Pete Keleher for the Alpha text editor; to the University of Washington Mathematics Research and Engineering libraries for access to their collections; and to the University of Washington Oceanography department for letting me borrow their tape drives to access my dusty old archives of Usenet postings.

Thanks to Tanmoy Bhattacharya for the example in question 11.10, to Arjan Kenter for the code in question 13.7, to Tomohiko Sakamoto for the code in question 20.31, and to Roger Miller for the line in question 11.35.

Thanks to all these people, all over the world, who have contributed to the FAQ list in various ways, by offering suggestions, corrections, constructive criticism, or other support: Jamshid Afshar, David Anderson, Tanner Andrews, Sudheer Apte, Joseph Arceneaux, Randall Atkinson, Rick Beem, Peter Bennett, Wayne Berke, Dan Bernstein, John Bickers, Gary Blaine, Yuan Bo, Dave Boutcher, Michael Bresnahan, Vincent Broman, Stan Brown, Joe Buehler, Kimberley Burchett, Gordon Burditt, Burkhard Burow, Conor P. Cahill, D'Arcy J.M. Cain, Christopher Calabrese, Ian Cargill, Paul Carter, Mike Chambers, Billy Chambless, Franklin Chen, Jonathan Chen, Raymond Chen, Richard Cheung, Ken Corbin, Ian Cottam, Russ Cox, Jonathan Coxhead, Lee Crawford, Steve Dahmer, Andrew Daviel, James Davies, John E. Davis, Ken Delong, Norm Diamond, Jeff Dunlop, Ray Dunn, Stephen M. Dunn, Michael J. Eager, Scott Ehrlich, Arno Eigenwillig, Dave Eisen, Bjorn Engsig, David Evans, Clive D.W. Feather, Dominic Feeley, Simao Ferraz, Chris Flatters, Rod Flores, Alexander Forst, Steve Fosdick, Jeff Francis, Tom Gambill, Dave Gillespie, Samuel Goldstein, Tim Goodwin, Alasdair Grant, Ron Guilmette, Michael Hafner, Tony Hansen, Elliotte Rusty Harold, Joe Harrington, Des Herriott, John Hascall, Ger Hobbelt, Dexter Holland & Co., Jos Horsmeier, Blair Houghton, James C. Hu, Chin Huang, David Hurt, Einar Indridason, Vladimir Ivanovic, Jon Jagger, Ke Jin, Kirk Johnson, Larry Jones, James Kew, Lawrence Kirby, Kin-ichi Kitano, the kittycat, Peter Klausler, Andrew Koenig, Tom Koenig, Adam Kolawa, Jukka Korpela, Ajoy Krishnan T, Markus Kuhn, Deepak Kulkarni, Oliver Laumann, John Lauro, Felix Lee, Mike Lee, Timothy J. Lee, Tony Lee, Marty Leisner, Don Libes, Brian Liedtke, Philip Lijnzaad, Keith Lindsay, Yen-Wei Liu, Paul Long, Christopher Lott, Tim Love, Tim McDaniel, Kevin McMahon, Stuart MacMartin, John R. MacMillan, Andrew Main, Bob Makowski, Evan Manning, Barry Margolin, George Matas, Brad Mears, Bill Mitchell, Mark Moraes, Darren Morby, Bernhard Muenzer, David Murphy, Walter Murray, Ralf Muschall, Ken Nakata, Todd Nathan, Landon Curt Noll, Tim Norman, Paul Nulsen, David O'Brien, Richard A. O'Keefe, Adam Kolawa, James Ojaste, Hans Olsson, Bob Peck, Andrew Phillips, Christopher Phillips, FranAois Pinard, Nick Pitfield, Wayne Pollock, Dan Pop, Lutz Prechelt, Lynn Pye, Kevin D. Quitt, Pat Rankin, Arjun Ray, Eric S. Raymond, Peter W. Richards, Eric Roode, Manfred Rosenboom, J. M. Rosenstock, Rick Rowe, Erkki Ruohtula, John Rushford, Rutabaga, Kadda Sahnine, Matthew Saltzman, Rich Salz, Chip Salzenberg, Matthew Sams, Paul Sand, David W. Sanderson, Frank Sandy, Christopher Sawtell, Jonas Schlein, Paul Schlyter, Doug Schmidt, Rene Schmit, Russell Schulz, Dean Schulze, Chris Sears, Patricia Shanahan, Raymond Shwake, Peter da Silva, Joshua Simons, Ross Smith, Henri Socha, Leslie J. Somos, David Spuler, James Stern, Bob Stout, Steve Sullivan, my sweetie Melanie Summit, Erik Talvola, Dave Taylor, Clarke Thatcher, Wayne Throop, Steve Traugott, Ilya Tsindlekht, Andrew Tucker, G'ran Uddeborg, Rodrigo Vanegas, Jim Van Zandt, Wietse Venema, Tom Verhoeff, Ed Vielmetti, Larry Virden, Chris Volpe, Mark Warren, Alan Watson, Kurt Watzka, Larry Weiss, Martin Weitzel, Howard West, Tom White, Freek Wiedijk, Dik T. Winter, Lars Wirzenius, Dave Wolverton, Mitch Wright, Conway Yee, Ozan S. Yigit, and Zhuo Zang. I have tried to keep track of everyone whose suggestions I have used, but I fear I've probably overlooked a few; my apologies to anyone whose name should be on this list, but isn't.

Finally, I'd like to thank my editor at Addison-Wesley, Debbie Lafferty, for tapping me on the electronic shoulder one day and asking if I might be interested in writing this book. I was, and you now hold it, and I hope that it may help to make C programming as pleasant for you as it is for me.

Steve Summit

Seattle, Washington




You've probably had the experience, in a bar or at a party, of losing a bet on whether you could perform some seemingly simple task which turned out, based on idiosyncrasies of the human body or the laws of physics, to be impossible. The guy making the bet knew that the more people he challenged, the more likely he was to keep winning, because those idiosyncrasies and laws, even if obscure, are fairly constant and predictable.

In a similar way, if you take a large number of people and set them at some complex task, such as learning the C programming language, many of them will run into exactly the same problems and have exactly the same questions. The questions and problems may or may not have been predictable when the task was first designed, and the answers may seem obvious in hindsight, but people will keep having some of the same problems, and the same questions will keep coming up. These problems and questions don't necessarily indicate that the task was impossible, but merely that it was difficult enough to be interesting.

Not surprisingly, these problems and questions are asked about all the time on the Internet, particularly in the interactive discussion newsgroups known as Usenet. The reasonably obvious idea of collecting the frequent questions gave rise to a tradition of Frequently Asked Questions or FAQ lists. FAQ lists don't always serve their intended purpose of reducing the incidence of frequently asked questions, but if the questions are in fact consistent, the fact that they were asked often enough to be selected for inclusion in an FAQ list suggests that they might match questions which you or some other readers of this book are asking, too.

About This Book

Most books (about C or any other topic) are written from the author's point of view. They discuss the topics the author thinks you should know, presented in a way which makes sense to the author. If that way doesn't make sense to you (and, at some level, it can't, because the author presumably knows the material already while you presumably don't), you may be left with deep, unanswered questions.

This book, however, is organized around some 400 of those questions, all based on real ones asked by real people attempting to learn or program in C. This book is not targeted at just those topics that the author thinks are important; it is targeted at the topics that real readers think are important, based on the questions they ask. The chances are good that if you are learning or using C, and you have a question about C which isn't answered in any of the other books you've checked, you'll find it answered here.

This book can't promise to answer every question you'll have when you're programming in C, since many of the questions that will come up in your programming will have to do with your problem domain, and this book covers only the C language itself. Just as it can't cover every aspect of every problem anyone might try to solve in C, this book cannot cover every aspect of every operating system which anyone might try to write a C program for, or every algorithm which anyone might try to implement in C. Specific problems, specific operating systems, and general-purpose algorithms are properly discussed in books or other materials devoted to those topics. Nevertheless, certain questions involving operating systems and algorithms are quite frequent, so chapters 19 and 20 provide brief, introductory answers to a few of them, but please don't expect the treatment to be complete.

The questions in this book are those that people typically have after reading an introductory C textbook or taking a C programming class. Therefore, this book will not teach you C, nor does it discuss fundamental issues which any C textbook should cover. Furthermore, this book's answers are intended for the most part to be definitively correct, and to avoid propagating any misconceptions. Therefore, a few answers are more elaborate than might at first seem necessary: they give you the complete picture, rather than oversimplifying or leaving out important details. (It is, after all, oversimplifications or omitted details which are behind many of the misconceptions which this book's questions and answers address.) Within the elaborate answers you will find shortcuts and simplifications where necessary, and in the Glossary beginning on page xxx you will find definitions of the precise terms which accurate explanations often demand. The shortcuts and simplifications are of course safe ones: they should not lead to later misunderstandings, and you can always come back to the more complete explanations, or pursue some of the references, if you later desire the full story.

As we'll see particularly in chapters 3 and 11, the standard definitions of C do not specify the behavior of every C program which can be written. Some programs fall into various gray areas: they may happen to work on some systems, and they may not be strictly illegal, but they are not guaranteed to work everywhere. This book is about portable C programming, so its answers advise against using nonportable constructs if at all possible.

The on-line FAQ list behind this book was written as a dialog: when people didn't understand it, they said so. That feedback has been invaluable in refining the form of the answers. Though a printed book is obviously more static, such a dialog is still appropriate: your comments, criticisms and suggestions are welcome. If you have access to the Internet, you may send comments to scs@aw.com, or you may send them on paper in care of the publisher. A list of any errata which are discovered in this book will be maintained and available on the Internet; see question 20.40 for information.

Question Format

The bulk of this book consists of a series of question/answer pairs. Many answers also contain references and notes. The notes, where they appear, are on the order of footnotes; you can skip them if you find that they're too picky. Several respected references are cited repeatedly, under these abbreviations:

  • ANSI The (original) ANSI C Standard, X3.159-1989
  • CT&P C Traps and Pitfalls, by Andrew Koenig
  • H&S Harbison and Steele, C: A Reference Manual, Fourth Edition
  • ISO The ISO C Standard, ISO 9899:1990
  • K&R1 Kernighan and Ritchie, The C Programming Language, First Edition
  • K&R2 Kernighan and Ritchie, The C Programming Language, Second Edition
  • PCS Portable C Software, by Mark Horton
  • Rationale The Rationale for the ANSI C Standard, X3.159-1989

Other references are cited by their full titles; full citations for all references appear in the Bibliography on page xxx.

This constant width typeface is used to indicate C syntax (function and variable names, keywords, etc.), and also to indicate a few operating system commands (cc, etc.). An occasional notation of the form tty(4) indicates the section "tty" in chapter 4 of the UNIX Programmer's manual.

Code Samples

This is a book about C, so many small pieces of it are necessarily written in C. The examples are written primarily for clarity of exposition. They are not always written in the most efficient way possible; making them "faster" would often make them less clear. (See question 20.13 for more information about code efficiency.) They are primarily written using modern, ANSI-style syntax; see question 11.29 for conversion tips if you're still using a "Classic" compiler.

The author and publisher invite you to use and modify these code fragments in your own programs, but of course we would appreciate acknowledgment if you do so. (Some fragments are from other sources, and are so attributed; please acknowledge those contributors if you use those codes.) The source code for the larger examp


Submit Errata

More Information

Unlimited one-month access with your purchase
Free Safari Membership