Notes to Accompany The C Programming Language, by Kernighan and Ritchie (``K&R''). Steve Summit homeranking.infoc Frequently Asked Questions. This page lists my favorite links having to do with C programming. Follow this link to download the C99 standard (INCITS/ISO/IEC ) in PDF form; homeranking.infoc FAQ — Steve Summit's FAQ list for the homeranking.infoc newsgroup is a. 9MKCODDDVG5N» Doc» C Programming FAQs: Frequently asked Questions. Find eBook Authored by Steve Summit. Released at -. Filesize: MB.
|Language:||English, Spanish, Portuguese|
|Country:||United Arab Emirates|
|Genre:||Science & Research|
|ePub File Size:||18.32 MB|
|PDF File Size:||10.61 MB|
|Distribution:||Free* [*Regsitration Required]|
faq/homeranking.info> is the right way to link to these Steve Summit, C Programming FAQs: Frequently Asked Questions, Addison-. A major revision and expansion of the homeranking.infoc FAQ list was published in late by Author: Steve Summit Title: C Programming FAQs: Frequently Asked. the book "The C Programming Language", by Kernighan and Ritchie, and it is very Another recommended source is "C Programming FAQs", by Steve Summit.
Thanks to the reviewers of the book-length version: System Dependencies At the present time. It might do so if calls using variable-length argument lists were less efficient than those using fixed-length. Are comments legal inside quoted strings?
Jan 12, Vladimir K rated it it was amazing. I have many years of experience writing C code, and while most answers were obvious to me, there were some that completely threw me out of my comfort zone and provided ample food for thought. I wholeheartedly recommend the book or the free online version of it to any C programmer with some prior experience who wants to know all the edge cases and "gotchas" of the language that are so frequently swept under the rug by many C programmers and book writers.
Jan 12, Ernesto rated it it was amazing. Every self-respecting programmer should know the answer to What is Duff's Device? Oct 05, JManInPhoenix rated it it was amazing. Not so much read as thumbed through. Will be keeping as a ready reference. Mar 23, Nick Black rated it it was amazing.
I'm absolutely shocked how often I still must quote comp. This is a more complete treatment of the classic Eskimo version of the FAQ than is available online; watch out for some slightly obsolete elements note that C99 is not addressed, but that's rarely important.
Apr 16, Roy Vanegas rated it it was amazing. An absolute must-have for any C programmer. If you find yourself tripping on C syntax and so many of us do, regardless of experience , Summit has very likely addressed the issue in this book. Dilip Sharma rated it liked it Oct 24, Daniel Souza rated it really liked it Oct 13, David rated it it was amazing Oct 09, David Lindelof rated it it was amazing Dec 26, Steven rated it really liked it Aug 14, Aditya rated it it was amazing Mar 02, Shivam rated it it was amazing Sep 14, Utkarsh Sengar rated it really liked it Dec 23, John rated it really liked it Jan 22, Shawn rated it it was amazing May 24, Robert Love rated it really liked it Mar 08, Daniel rated it liked it Aug 12, Vinber Lei rated it it was amazing May 30, Ian rated it really liked it Mar 25, Sandhya rated it did not like it Jun 11, Salahuddin Ansari rated it it was amazing Sep 03, Seong-Kook Shin rated it it was amazing Jul 28, Anup rated it it was amazing Feb 11, Ayush Bhat rated it it was amazing Apr 28, Kandarp Jani rated it it was amazing Jul 22, Raghu rated it it was amazing Apr 02, Fred Milano rated it really liked it Aug 05, Cal Desmond-Pearson rated it really liked it Jun 28, AK added it Apr 21, Hemant marked it as to-read Oct 11, Bahar is currently reading it May 27, Manuel Menezes de Sequeira added it Jul 05, Igor Furnas marked it as to-read Dec 11, Rishad marked it as to-read Apr 15, Darin added it Jul 01, Christopher added it Jul 25, Ben added it Jul 30, Vishal Darbar marked it as to-read Aug 18, Michael added it Feb 27, James added it Apr 06, Kartik Singhal marked it as to-read Jun 25, Pavithra V marked it as to-read Jul 20, Danica Joy marked it as to-read Aug 01, An excellent reference manual is C: Mitch Wright maintains an annotated bibliography of C and Unix books.
Though not suitable for learning C from scratch. There are far too many books on C to list here. This FAQ list's editor maintains a collection of previous answers to this question. Many people believe that the best one was also the first: See also questions 2. Either pass pointers to several locations which the function can fill in. Software Solutions in C Sec. They are pointed to by the argv array with which main is called. If you must use a binary format.
Not only is their efficiency frequently acceptable in practice. Be skeptical of arguments which imply that text files are too big. Similar advice also applies to network protocols. The most straightforward thing to do is to maintain a correspondence table of names and function pointers: Use arrays of char or int.
Here are some simple macros to use with arrays of char: One way is to use a pointer: It's also possible to use a union. Integers are stored internally in binary. Make sure you really know what you're asking. The base in which a number is expressed matters only when that number is read in from or written out to the outside world. In source code. ANSI Secs. See also questions 8. You can convert base-2 string representations to integers with strtol.
When efficiency is a concern. For more discussion of efficiency tradeoffs. Most of the code in most programs is not time-critical. In any case. Heavyhanded optimization attempts can make code so bulky that performance is actually degraded. Remember that computers are very. When code is not time-critical. Even for code that is time-critical. Precise answers to these and many similar questions depend of course on the processor and compiler in use. Often the differences are so slight that hundreds of thousands of iterations are required even to see them.
See also question 3. Check the compiler's assembly language output. Function calls. If you simply must know. See also questions Not directly. If you want to select on arbitrary ranges or non-constant expressions. See also questions question The switch statement was originally designed to be quite simple for the compiler to translate.
You can attach several case labels to the same statement. Long ago. As it happens. How am I supposed to comment out code containing comments?
Are comments legal inside quoted strings? Annex F Rationale Sec. A cleaner solution when such functions must communicate is to pass around a pointer to a structure containing the necessary context.
For many potential uses of nested functions e. It's not trivial to implement nested functions such that they have the proper access to local variables in the containing function s. Read your compiler documentation very carefully. More information may be found in FORT.
And vice versa? The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use.
It is available via anonymous ftp from zebra. It is also available via anonymous ftp on netlib. Volume This FAQ list's maintainer also has available a list of a few other commercial translation products. Several freely distributable programs are available: To find out more about f2c.
In spite of the differences.
Soundex was designed for discovering similar-sounding names for telephone directory assistance. Knuth Sec. Some nice information and algorithms having to do with approximate string matching.
Hashing is the process of mapping strings to integers. Use mktime or localtime see questions ANSI Sec. To forestall an eternal debate: Yes and no.
It is actually quite difficult to write a self-reproducing program that is truly portable. Here is a classic example which is normally presented on one line. It's a devastatingly deviously unrolled byte-copying loop.
Believe it or not. It solves the problem of handling the leftover bytes when count isn't a multiple of 8 by interleaving a switch statement with the loop which copies bytes 8 at a time.
In his announcement of the technique to C's developers and the world. Duff noted that C's switch syntax. To obtain a current copy of the rules and guidelines. Winning entries from previous years back to are archived at ftp.
How can I get a copy of the current and previous winning entries? As a last resort. It was reserved to allow the possibility of having functions with multiple. It has been withdrawn.
See also question 1. It was not. Declarations and Initializations 1. Is this legal or portable? Regardless of the order of evaluation. Expressions 3. Pointers 4. How can I pass a constant like 5 to it? I just can't understand all this null pointer stuff. NULL is guaranteed to be 0. Null Pointers 5. Null Pointers top http: Arrays and Pointers 6. Why didn't it work? How can this be legal C?
Why can I only seem to malloc K or so? Memory Allocation 7. How am I supposed to know to allocate things? Is this legal? Characters and Strings 8. Boolean Expressions and Variables 9. What do y'all think? C Preprocessor " define Paste a. What should I use instead?
How can I avoid overflowing the destination buffer with sprintf? I get the same sequence of numbers back from rand. What can I do? Variable-Length Argument Lists top http: Is it worthwhile? Isn't that a bit extreme? What about function keys?
Use sockets? Do networking? How can I write ISR's? How can I create TSR's? Conor P. James Stern. Mike Lee. Jonathan Chen. John Rushford. Guy Harris. Chris Torek. Bjorn Engsig. Lutz Prechelt. Frank Sandy. Joshua Simons.
Ralf Muschall. Andrew Tucker. James Kew. Felix Lee. Marty Leisner. Adam Kolawa. Bernhard Muenzer. Leslie J. Dan Pop. Russ Cox. Matthew Sams. Pat Rankin. Bob Makowski. Eric S. Lawrence Kirby. Erkki Ruohtula. Wayne Berke. Clarke Thatcher. Markus Kuhn. David Spuler. Peter Klausler. Wayne Pollock. Alasdair Grant. Christopher Phillips. Einar Indridason. Evan Manning. David Evans. Billy Chambless. Michael Bresnahan. Steve Clamage. Rich Salz. James C. Richard Cheung. Dave Eisen.
Michael J. Vladimir Ivanovic. Ilya Tsindlekht. Kirk Johnson. Peter da Silva. Mike Chambers.
Steve Dahmer. Tanmoy Bhattacharya. Russell Schulz. Barry Margolin. Arjan Kenter. Larry Jones. Rene Schmit. Stephen M. David Anderson. Rick Rowe. Yuan Bo. James Davies. Paul Schlyter. John R. Chip Salzenberg. D'Arcy J. Ken Corbin. Lynn Pye. Dave Gillespie. Joe Harrington. Richard A. Henri Socha. John Hascall. Tim Norman. John Bickers. Lee Crawford. Nick Pitfield. Michael Hafner. Clive D. Kadda Sahnine. Bob Peck. Ken Delong. Brian Liedtke. James Ojaste.
Landon Curt Noll. Deepak Kulkarni. Blair Houghton. Joe Buehler. Ger Hobbelt. Dan Bernstein. Bill Mitchell. Tanner Andrews. Matthew Saltzman. Kin-ichi Kitano. Ian Cargill. Erik Talvola. Burkhard Burow. Norm Diamond. Paul Nulsen. Bob Stout. Chris Flatters. Yen-Wei Liu. Acknowledgements Acknowledgements Thanks to Jamshid Afshar.
David Murphy. Joseph Arceneaux. Ke Jin. Tim Love. DaviD W. Sudheer Apte. Raymond Chen. Jon Jagger. David Hurt. John E. Samuel Goldstein. Scott Ehrlich. Ray Dunn. Brad Mears. Des Herriott. Dave Taylor. Tony Lee. Stan Brown. Ian Cottam. Doug Gwyn. Andrew Daviel. Manfred Rosenboom. Alexander Forst. Kimberley Burchett. Timothy J. Jonas Schlein. Patricia Shanahan.
Kevin McMahon. Walter Murray. Stuart MacMartin. Franklin Chen. Tom Gambill. Tim Goodwin. Jos Horsmeier. Andrew Koenig. Philip Lijnzaad. Tony Hansen. Andrew Phillips. Paul Sand. Wayne Throop. Steve Traugott. David O'Brien. Eric Roode. Andrew Main. Ajoy Krishnan T. Ron Guilmette. Dave Boutcher. Kevin D. Henry Spencer. Keith Lindsay. Todd Nathan. Vinit Carpenter. Christopher Calabrese. Don Libes. Jeff Francis. Gordon Burditt. Arjun Ray. Oliver Laumann. Roger Miller. Peter W.
Rod Flores. Chin Huang. Rick Beem. Simao Ferraz. Jeff Dunlop. Raymond Shwake. Dominic Feeley. Tomohiko Sakamoto. Chris Sears. Elliotte Rusty Harold. Jutta Degener. Randall Atkinson. Tom Koenig. Paul Long. George Matas. Tim McDaniel. Hans Olsson. Paul Carter. Ross Smith. Christopher Lott. Mark Moraes. Steve Sullivan. Dean Schulze. Steve Fosdick. Peter Bennett. Doug Schmidt. Melanie Summit. Gary Blaine. Christopher Sawtell.
John Lauro. Darren Morby. Vincent Broman. Jonathan Coxhead. Arno Eigenwillig. Ken Nakata. Jukka Korpela. Stephen Clamage. Dik T. Lars Wirzenius. Wietse Venema. Mitch Wright. Thanks to the reviewers of the book-length version: Mark Brader. Acknowledgements Uddeborg. Jim Van Zandt. Dave Wolverton. Special thanks to Karl Heuer. Conway Yee. Tom White.
Rodrigo Vanegas. Ozan S. Howard West. Mark Warren. Tom Verhoeff. Larry Virden. Ed Vielmetti. Freek Wiedijk. Karl Heuer. Larry Weiss. Chris Volpe. Kurt Watzka. Martin Weitzel. Thanks to Jukka Korpela and Jutta Degener for providing interim versions of this list in web form while I was dragging my feet.
Alan Watson. Questions 1. Questions 2. Why doesn't " int http: Questions 5. Questions 6. Questions 7. Questions Questions undefined behavior?
Variable-Length Argument Lists http: If you might need large values above 32, or below , , use long. Otherwise, if space is very important i. Otherwise, use int. If well-defined overflow characteristics are important and negative values are not, or if you want to steer clear of signextension problems when manipulating bits or bytes, use one of the corresponding unsigned types.
Beware when mixing signed and unsigned values in expressions, though. Using unsigned char can help; see question None of the above rules apply if the address of a variable is taken and must have a particular type. If for some reason you need to declare something with an exact size usually the only good reason for doing so is when attempting to conform to some externally-imposed storage layout, but see question B11 p.
For one thing, the variable to hold getchar's return value must be an int. By passing getchar's return value through a char, either a normal character might be misinterpreted as EOF, or the EOF might be altered particularly if type char is unsigned and so never seen. Some vendors of C products for bit machines support bit long ints.
Programmers interested in writing portable code should therefore insulate their 64bit type needs behind appropriate typedefs. The definition is the declaration that actually allocates space, and provides an initialization value, if any.
The best arrangement is to place each definition in some relevant. This rule promotes a high degree of portability: A few very odd systems may require an explicit initializer to distinguish a definition from an external declaration. It is possible to use preprocessor tricks to arrange that a line like DEFINE int, i ; need only be entered once in one header file, and turned into a definition or a declaration depending on the setting of some macro, but it's not clear if this is worth the trouble.
It's especially important to put global declarations in header files if you want the compiler to catch inconsistent declarations for you. In particular, never place a prototype for an external function in a.
ISO Sec. As a general rule, you should put these things in header. In particular, never put external function prototypes in. On the other hand, when a definition or declaration should remain private to one source file, it's fine to leave it there. See also questions 1. Not really. First of all. See questions 1. If you do want to use function prototypes instead of lint for cross-file consistency checking.
Question 1. It can be used as a stylistic hint to indicate that the function's definition is probably in another source file. Can't a structure in C contain a pointer to itself?
Structures in C can certainly contain pointers to themselves. See also question 2. To fix this code. A similar problem. The main difference is that the second declaration is of a slightly more abstract type--its users don't necessarily know that it is a structure. The first form declares a structure tag.. Question 2. Use the cdecl program. The pointer-to-function declarations in the examples above have not included parameter type information. The first part of this question can be answered in at least three ways: Modern versions of cdecl can help here.
Versions of cdecl are in volume 14 of comp. When the parameters have complicated types. Build the declaration up incrementally. Either have the function return a generic function pointer. But I can't find a way to declare the functions.
I'm building a state machine with one function for each state. You can't quite do it directly. Functions which are called without a declaration in scope perhaps because the first call precedes the function's definition are assumed to be declared as returning int and without any argument type information.
Another possible source of this problem is that the function has the same name as another one declared in some header file. Non-int functions must be declared before they are called.
This problem can be fixed either by using new-style syntax consistently in the definition: In this case. For old-style function definitions. It is usually safe to mix the two styles see question It might do so if calls using variable-length argument lists were less efficient than those using fixed-length. A compiler may use a different calling sequence for functions which accept variablelength argument lists.
So that a proper prototype for printf will be in scope. Variables with static duration that is. Memory obtained with calloc is all-bits Dynamically-allocated memory obtained with malloc and realloc is also likely to contain garbage.
Variables with automatic duration i. Nothing useful can be predicted about the garbage. Question 7. Is it safe to take advantage of calloc's zero-filling? Does free work on memory allocated with calloc, or do you need a cfree? As a workaround, you can make the array global or static if you won't need a fresh copy during any subsequent calls , or replace it with a pointer if the array won't be written to.
If neither of these conditions hold, you'll have to initialize the array by hand with strcpy when f is called. A string literal can be used in two slightly different ways. As an array initializer as in the declaration of char a , it specifies the initial values of the characters in that array. Anywhere else, it turns into an unnamed, static array of characters, which may be stored in read-only memory, which is why you can't safely modify it.
In an expression context, the array is converted at once to a pointer, as usual see section 6 , so the second declaration initializes p to point to the unnamed array's first element.
For compiling old code, some compilers have a switch controlling whether strings are writable or not. Perhaps it is a pre-ANSI compiler, unable to accept function prototypes and the like. Question 6. The type pointer-to-type-T is not the same as array-of-type-T.
Use extern char a. Not at all. What you heard has to do with formal parameters to functions; see question 6. Arrays are not pointers. As usual, a picture is worth a thousand words. In other words, a is three places past the start of the object named a, while p is three places past the object pointed to by p. In the example above, both a and p happen to be the character 'l', but the compiler gets there differently.
Arrays automatically allocate space, but can't be relocated or resized. Pointers must be explicitly assigned to point to allocated space perhaps using malloc , but can be reassigned i. Due to the so-called equivalence of arrays and pointers see question 6.
See questions 6. Be careful with sizeof, though. An explicit declaration for the function is normally needed, since implicit external function declaration does not happen in this case because the function name in the initialization is not part of a function call. See also question 4. Question 4. What's the story? The usage has always been unambiguous; there is nothing you ever could have done with a function pointer followed by an argument list except call the function pointed to.
Typedef names are not automatically generated for structure tags. One good way is for clients to use structure pointers perhaps additionally hidden behind typedefs which point to structure types which are not publicly defined.
Another possibility is to declare the variable-size element very large. A thorough treatment of the arguments surrounding the legality of the technique is beyond the scope of this list.
Rationale Sec. This technique is popular. It does seem to be portable to all known implementations Compilers which check array bounds carefully might issue warnings. Although a few early C compilers lacked these operations. Footnote 1 However. There is no single. A field-by-field comparison might require unacceptable amounts of repetitive code for large structures. If you need to compare two structures.
Can I turn off the padding. Your compiler may provide an extension to give you this control perhaps a pragma. When structures are passed as arguments to functions. Programmers often choose to use pointers to structures instead. Structures are often returned from functions in a location pointed to by an extra.
Some compilers merely pass a pointer to the structure. Some older compilers used a special. C has no way of generating anonymous structure values. You will have to use a temporary structure variable or a little structure-building function. It is straightforward to define a simple structure and some arithmetic functions to manipulate them. How can I pass a constant by reference? You can't do this directly. You will have to declare a temporary variable.
A more portable solution. It is relatively straightforward to write a structure out using fwrite: What's important is that fwrite receive a byte pointer.
Note also that if the structure contains any pointers. When you're reading a binary data file. I'm occasionally seeing 0x0a and 0x0d values getting garbled.
The pragma directive provides a single. Even when the structure is not part of an array. See question 2. Structures may have this padding as well as internal padding.
ANSI C defines the offsetof macro. If you don't have it. Build a table of names and offsets. Since structurevalued functions are usually implemented by adding a hidden return pointer see question 2.
The connection is hard to see because of the intervening comment. Perhaps there's a missing semicolon at the end of the last declaration in the last header file you're including. What could be causing this? Look for a misdeclared main see questions 2.
See also questions 7. There is no standard way of initializing any other member nor. If such intermixing were disallowed without explicit casts.