home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / C-faq / faq < prev    next >
Encoding:
Internet Message Format  |  2004-03-02  |  266.2 KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!newsfeed.stanford.edu!headwall.stanford.edu!newshub.sdsu.edu!elnk-nf2-pas!elnk-pas-nf1!newsfeed.earthlink.net!newsfeed3.easynews.com!newsfeed1.easynews.com!easynews.com!easynews!news-stk-2.sprintlink.net!news-west.sprintlink.net!news-in-west1.sprintlink.net!news.sprintlink.net!news.eskimo.com!eskimo.com!scs
  2. From: scs@eskimo.com (Steve Summit)
  3. Newsgroups: comp.lang.c,comp.lang.c.moderated,comp.answers,news.answers
  4. Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
  5. Followup-To: poster
  6. Date: 1 Mar 2004 11:00:11 GMT
  7. Organization: better late than never
  8. Lines: 6929
  9. Approved: news-answers-request@MIT.Edu
  10. Expires: 3 Apr 2004 00:00:00 GMT
  11. Message-ID: <2004Mar01.0600.scs.0001@eskimo.com>
  12. Reply-To: scs@eskimo.com
  13. NNTP-Posting-Host: eskimo.com
  14. X-Trace: eskinews.eskimo.com 1078138811 23650 204.122.16.13 (1 Mar 2004 11:00:11 GMT)
  15. X-Complaints-To: abuse@eskimo.com
  16. NNTP-Posting-Date: 1 Mar 2004 11:00:11 GMT
  17. X-Last-Modified: February 7, 1999
  18. X-Archive-Name: C-faq/faq
  19. X-Version: 3.5
  20. X-URL: http://www.eskimo.com/~scs/C-faq/top.html
  21. X-PGP-Signature: Version: 2.6.2
  22.     iQCSAwUBNr5mkN6sm4I1rmP1AQEr/APoniUefFSgXsFWaMy+nDcCCzvH9phH7BVx
  23.     0CwFcGKz/udQ6DsXSynb3d9i50DUeRUXP2RcY69dmV41SZrBraQmXjjlwAulRlqB
  24.     mDzL9zAhlQOSaS33s6zYmUB4A4kq+61XRYGGFwBc5dSWCzTlzxbl1nWo5Uru+azJ
  25.     9MKtfOg=
  26.     =f2Ny
  27. Originator: scs@eskimo.com
  28. Xref: senator-bedfellow.mit.edu comp.lang.c:679369 comp.lang.c.moderated:26474 comp.answers:56421 news.answers:267258
  29.  
  30. Archive-name: C-faq/faq
  31. Comp-lang-c-archive-name: C-FAQ-list
  32. URL: http://www.eskimo.com/~scs/C-faq/top.html
  33.  
  34. [Last modified February 7, 1999 by scs.]
  35.  
  36. This article is Copyright 1990-1999 by Steve Summit.  Content from the
  37. book _C Programming FAQs: Frequently Asked Questions_ is made available
  38. here by permission of the author and the publisher as a service to the
  39. community.  It is intended to complement the use of the published text
  40. and is protected by international copyright laws.  The content is made
  41. available here and may be accessed freely for personal use but may not
  42. be republished without permission.
  43.  
  44. Certain topics come up again and again on this newsgroup.  They are good
  45. questions, and the answers may not be immediately obvious, but each time
  46. they recur, much net bandwidth and reader time is wasted on repetitive
  47. responses, and on tedious corrections to the incorrect answers which are
  48. inevitably posted.
  49.  
  50. This article, which is posted monthly, attempts to answer these common
  51. questions definitively and succinctly, so that net discussion can move
  52. on to more constructive topics without continual regression to first
  53. principles.
  54.  
  55. No mere newsgroup article can substitute for thoughtful perusal of a
  56. full-length tutorial or language reference manual.  Anyone interested
  57. enough in C to be following this newsgroup should also be interested
  58. enough to read and study one or more such manuals, preferably several
  59. times.  Some C books and compiler manuals are unfortunately inadequate;
  60. a few even perpetuate some of the myths which this article attempts to
  61. refute.  Several noteworthy books on C are listed in this article's
  62. bibliography; see also questions 18.9 and 18.10.  Many of the questions
  63. and answers are cross-referenced to these books, for further study by
  64. the interested and dedicated reader.
  65.  
  66. If you have a question about C which is not answered in this article,
  67. first try to answer it by checking a few of the referenced books, or by
  68. asking knowledgeable colleagues, before posing your question to the net
  69. at large.  There are many people on the net who are happy to answer
  70. questions, but the volume of repetitive answers posted to one question,
  71. as well as the growing number of questions as the net attracts more
  72. readers, can become oppressive.  If you have questions or comments
  73. prompted by this article, please reply by mail rather than following up --
  74. this article is meant to decrease net traffic, not increase it.
  75.  
  76. Besides listing frequently-asked questions, this article also summarizes
  77. frequently-posted answers.  Even if you know all the answers, it's worth
  78. skimming through this list once in a while, so that when you see one of
  79. its questions unwittingly posted, you won't have to waste time
  80. answering.  (However, this is a large and heavy document, so don't
  81. assume that everyone on the newsgroup has managed to read all of it in
  82. detail, and please don't roll it up and thwack people over the head with
  83. it just because they missed their answer in it.)
  84.  
  85. This article was last modified on February 7, 1999, and its travels may
  86. have taken it far from its original home on Usenet.  It may, however,
  87. be out-of-date, particularly if you are looking at a printed copy
  88. or one retrieved from a tertiary archive site or CD-ROM.  You should
  89. be able to obtain the most up-to-date copy on the web at
  90. http://www.eskimo.com/~scs/C-faq/top.html or http://www.faqs.org/faqs/ ,
  91. or from one of the ftp sites mentioned in question 20.40.  Since this
  92. list is modified from time to time, its question numbers may not match
  93. those in older or newer copies which are in circulation; be careful when
  94. referring to FAQ list entries by number alone.
  95.  
  96. This article was produced for free redistribution.  You should not need
  97. to pay anyone for a copy of it.
  98.  
  99. Other versions of this document are also available.  Posted along with
  100. it are an abridged version and (when there are changes) a list of
  101. differences with respect to the previous version.  A hypertext version
  102. is available on the web at the aforementioned URL.  Finally, for those
  103. who might prefer a bound, hardcopy version (and even longer answers to
  104. even more questions!), a book-length version has been published by
  105. Addison-Wesley (ISBN 0-201-84519-9).
  106.  
  107. This article is always being improved.  Your input is welcomed.  Send
  108. your comments to scs@eskimo.com .
  109.  
  110. The questions answered here are divided into several categories:
  111.  
  112.      1. Declarations and Initializations
  113.      2. Structures, Unions, and Enumerations
  114.      3. Expressions
  115.      4. Pointers
  116.      5. Null Pointers
  117.      6. Arrays and Pointers
  118.      7. Memory Allocation
  119.      8. Characters and Strings
  120.      9. Boolean Expressions and Variables
  121.     10. C Preprocessor
  122.     11. ANSI/ISO Standard C
  123.     12. Stdio
  124.     13. Library Functions
  125.     14. Floating Point
  126.     15. Variable-Length Argument Lists
  127.     16. Strange Problems
  128.     17. Style
  129.     18. Tools and Resources
  130.     19. System Dependencies
  131.     20. Miscellaneous
  132.         Bibliography
  133.         Acknowledgements
  134.  
  135. (The question numbers within each section are not always continuous,
  136. because they are aligned with the aforementioned book-length version,
  137. which contains even more questions.)
  138.  
  139. Herewith, some frequently-asked questions and their answers:
  140.  
  141.  
  142. Section 1. Declarations and Initializations
  143.  
  144. 1.1:    How do you decide which integer type to use?
  145.  
  146. A:    If you might need large values (above 32,767 or below -32,767),
  147.     use long.  Otherwise, if space is very important (i.e. if there
  148.     are large arrays or many structures), use short.  Otherwise, use
  149.     int.  If well-defined overflow characteristics are important and
  150.     negative values are not, or if you want to steer clear of sign-
  151.     extension problems when manipulating bits or bytes, use one of
  152.     the corresponding unsigned types.  (Beware when mixing signed
  153.     and unsigned values in expressions, though.)
  154.  
  155.     Although character types (especially unsigned char) can be used
  156.     as "tiny" integers, doing so is sometimes more trouble than it's
  157.     worth, due to unpredictable sign extension and increased code
  158.     size.  (Using unsigned char can help; see question 12.1 for a
  159.     related problem.)
  160.  
  161.     A similar space/time tradeoff applies when deciding between
  162.     float and double.  None of the above rules apply if the address
  163.     of a variable is taken and must have a particular type.
  164.  
  165.     If for some reason you need to declare something with an *exact*
  166.     size (usually the only good reason for doing so is when
  167.     attempting to conform to some externally-imposed storage layout,
  168.     but see question 20.5), be sure to encapsulate the choice behind
  169.     an appropriate typedef.
  170.  
  171.     References: K&R1 Sec. 2.2 p. 34; K&R2 Sec. 2.2 p. 36, Sec. A4.2
  172.     pp. 195-6, Sec. B11 p. 257; ISO Sec. 5.2.4.2.1, Sec. 6.1.2.5;
  173.     H&S Secs. 5.1,5.2 pp. 110-114.
  174.  
  175. 1.4:    What should the 64-bit type on a machine that can support it?
  176.  
  177. A:    The forthcoming revision to the C Standard (C9X) specifies type
  178.     long long as effectively being at least 64 bits, and this type
  179.     has been implemented by a number of compilers for some time.
  180.     (Others have implemented extensions such as __longlong.)
  181.     On the other hand, there's no theoretical reason why a compiler
  182.     couldn't implement type short int as 16, int as 32, and long int
  183.     as 64 bits, and some compilers do indeed choose this
  184.     arrangement.
  185.  
  186.     See also question 18.15d.
  187.  
  188.     References: C9X Sec. 5.2.4.2.1, Sec. 6.1.2.5.
  189.  
  190. 1.7:    What's the best way to declare and define global variables
  191.     and functions?
  192.  
  193. A:    First, though there can be many "declarations" (and in many
  194.     translation units) of a single "global" (strictly speaking,
  195.     "external") variable or function, there must be exactly one
  196.     "definition".  (The definition is the declaration that actually
  197.     allocates space, and provides an initialization value, if any.)
  198.     The best arrangement is to place each definition in some
  199.     relevant .c file, with an external declaration in a header
  200.     (".h") file, which is #included wherever the declaration is
  201.     needed.  The .c file containing the definition should also
  202.     #include the same header file, so that the compiler can check
  203.     that the definition matches the declarations.
  204.  
  205.     This rule promotes a high degree of portability: it is
  206.     consistent with the requirements of the ANSI C Standard, and is
  207.     also consistent with most pre-ANSI compilers and linkers.  (Unix
  208.     compilers and linkers typically use a "common model" which
  209.     allows multiple definitions, as long as at most one is
  210.     initialized; this behavior is mentioned as a "common extension"
  211.     by the ANSI Standard, no pun intended.  A few very odd systems
  212.     may require an explicit initializer to distinguish a definition
  213.     from an external declaration.)
  214.  
  215.     It is possible to use preprocessor tricks to arrange that a line
  216.     like
  217.  
  218.         DEFINE(int, i);
  219.  
  220.     need only be entered once in one header file, and turned into a
  221.     definition or a declaration depending on the setting of some
  222.     macro, but it's not clear if this is worth the trouble.
  223.  
  224.     It's especially important to put global declarations in header
  225.     files if you want the compiler to catch inconsistent
  226.     declarations for you.  In particular, never place a prototype
  227.     for an external function in a .c file: it wouldn't generally be
  228.     checked for consistency with the definition, and an incompatible
  229.     prototype is worse than useless.
  230.  
  231.     See also questions 10.6 and 18.8.
  232.  
  233.     References: K&R1 Sec. 4.5 pp. 76-7; K&R2 Sec. 4.4 pp. 80-1; ISO
  234.     Sec. 6.1.2.2, Sec. 6.7, Sec. 6.7.2, Sec. G.5.11; Rationale
  235.     Sec. 3.1.2.2; H&S Sec. 4.8 pp. 101-104, Sec. 9.2.3 p. 267; CT&P
  236.     Sec. 4.2 pp. 54-56.
  237.  
  238. 1.11:    What does extern mean in a function declaration?
  239.  
  240. A:    It can be used as a stylistic hint to indicate that the
  241.     function's definition is probably in another source file, but
  242.     there is no formal difference between
  243.  
  244.         extern int f();
  245.  
  246.     and
  247.  
  248.         int f();
  249.  
  250.     References: ISO Sec. 6.1.2.2, Sec. 6.5.1; Rationale
  251.     Sec. 3.1.2.2; H&S Secs. 4.3,4.3.1 pp. 75-6.
  252.  
  253. 1.12:    What's the auto keyword good for?
  254.  
  255. A:    Nothing; it's archaic.  See also question 20.37.
  256.  
  257.     References: K&R1 Sec. A8.1 p. 193; ISO Sec. 6.1.2.4, Sec. 6.5.1;
  258.     H&S Sec. 4.3 p. 75, Sec. 4.3.1 p. 76.
  259.  
  260. 1.14:    I can't seem to define a linked list successfully.  I tried
  261.  
  262.         typedef struct {
  263.             char *item;
  264.             NODEPTR next;
  265.         } *NODEPTR;
  266.  
  267.     but the compiler gave me error messages.  Can't a structure in C
  268.     contain a pointer to itself?
  269.  
  270. A:    Structures in C can certainly contain pointers to themselves;
  271.     the discussion and example in section 6.5 of K&R make this
  272.     clear.  The problem with the NODEPTR example is that the typedef
  273.     has not been defined at the point where the "next" field is
  274.     declared.  To fix this code, first give the structure a tag
  275.     ("struct node").  Then, declare the "next" field as a simple
  276.     "struct node *", or disentangle the typedef declaration from the
  277.     structure definition, or both.  One corrected version would be
  278.  
  279.         struct node {
  280.             char *item;
  281.             struct node *next;
  282.         };
  283.  
  284.         typedef struct node *NODEPTR;
  285.  
  286.     and there are at least three other equivalently correct ways of
  287.     arranging it.
  288.  
  289.     A similar problem, with a similar solution, can arise when
  290.     attempting to declare a pair of typedef'ed mutually referential
  291.     structures.
  292.  
  293.     See also question 2.1.
  294.  
  295.     References: K&R1 Sec. 6.5 p. 101; K&R2 Sec. 6.5 p. 139; ISO
  296.     Sec. 6.5.2, Sec. 6.5.2.3; H&S Sec. 5.6.1 pp. 132-3.
  297.  
  298. 1.21:    How do I declare an array of N pointers to functions returning
  299.     pointers to functions returning pointers to characters?
  300.  
  301. A:    The first part of this question can be answered in at least
  302.     three ways:
  303.  
  304.     1.  char *(*(*a[N])())();
  305.  
  306.     2.  Build the declaration up incrementally, using typedefs:
  307.  
  308.         typedef char *pc;    /* pointer to char */
  309.         typedef pc fpc();    /* function returning pointer to char */
  310.         typedef fpc *pfpc;    /* pointer to above */
  311.         typedef pfpc fpfpc();    /* function returning... */
  312.         typedef fpfpc *pfpfpc;    /* pointer to... */
  313.         pfpfpc a[N];        /* array of... */
  314.  
  315.     3.  Use the cdecl program, which turns English into C and vice
  316.         versa:
  317.  
  318.         cdecl> declare a as array of pointer to function returning
  319.             pointer to function returning pointer to char
  320.         char *(*(*a[])())()
  321.  
  322.         cdecl can also explain complicated declarations, help with
  323.         casts, and indicate which set of parentheses the arguments
  324.         go in (for complicated function definitions, like the one
  325.         above).  See question 18.1.
  326.  
  327.     Any good book on C should explain how to read these complicated
  328.     C declarations "inside out" to understand them ("declaration
  329.     mimics use").
  330.  
  331.     The pointer-to-function declarations in the examples above have
  332.     not included parameter type information.  When the parameters
  333.     have complicated types, declarations can *really* get messy.
  334.     (Modern versions of cdecl can help here, too.)
  335.  
  336.     References: K&R2 Sec. 5.12 p. 122; ISO Sec. 6.5ff (esp.
  337.     Sec. 6.5.4); H&S Sec. 4.5 pp. 85-92, Sec. 5.10.1 pp. 149-50.
  338.  
  339. 1.22:    How can I declare a function that can return a pointer to a
  340.     function of the same type?  I'm building a state machine with
  341.     one function for each state, each of which returns a pointer to
  342.     the function for the next state.  But I can't find a way to
  343.     declare the functions.
  344.  
  345. A:    You can't quite do it directly.  Either have the function return
  346.     a generic function pointer, with some judicious casts to adjust
  347.     the types as the pointers are passed around; or have it return a
  348.     structure containing only a pointer to a function returning that
  349.     structure.
  350.  
  351. 1.25:    My compiler is complaining about an invalid redeclaration of a
  352.     function, but I only define it once and call it once.
  353.  
  354. A:    Functions which are called without a declaration in scope
  355.     (perhaps because the first call precedes the function's
  356.     definition) are assumed to be declared as returning int (and
  357.     without any argument type information), leading to discrepancies
  358.     if the function is later declared or defined otherwise.  Non-int
  359.     functions must be declared before they are called.
  360.  
  361.     Another possible source of this problem is that the function has
  362.     the same name as another one declared in some header file.
  363.  
  364.     See also questions 11.3 and 15.1.
  365.  
  366.     References: K&R1 Sec. 4.2 p. 70; K&R2 Sec. 4.2 p. 72; ISO
  367.     Sec. 6.3.2.2; H&S Sec. 4.7 p. 101.
  368.  
  369. 1.25b:    What's the right declaration for main()?
  370.     Is void main() correct?
  371.  
  372. A:    See questions 11.12a to 11.15.  (But no, it's not correct.)
  373.  
  374. 1.30:    What am I allowed to assume about the initial values
  375.     of variables which are not explicitly initialized?
  376.     If global variables start out as "zero", is that good
  377.     enough for null pointers and floating-point zeroes?
  378.  
  379. A:    Uninitialized variables with "static" duration (that is, those
  380.     declared outside of functions, and those declared with the
  381.     storage class static), are guaranteed to start out as zero, as
  382.     if the programmer had typed "= 0".  Therefore, such variables
  383.     are implicitly initialized to the null pointer (of the correct
  384.     type; see also section 5) if they are pointers, and to 0.0 if
  385.     they are floating-point.
  386.  
  387.     Variables with "automatic" duration (i.e. local variables
  388.     without the static storage class) start out containing garbage,
  389.     unless they are explicitly initialized.  (Nothing useful can be
  390.     predicted about the garbage.)
  391.  
  392.     Dynamically-allocated memory obtained with malloc() and
  393.     realloc() is also likely to contain garbage, and must be
  394.     initialized by the calling program, as appropriate.  Memory
  395.     obtained with calloc() is all-bits-0, but this is not
  396.     necessarily useful for pointer or floating-point values (see
  397.     question 7.31, and section 5).
  398.  
  399.     References: K&R1 Sec. 4.9 pp. 82-4; K&R2 Sec. 4.9 pp. 85-86; ISO
  400.     Sec. 6.5.7, Sec. 7.10.3.1, Sec. 7.10.5.3; H&S Sec. 4.2.8 pp. 72-
  401.     3, Sec. 4.6 pp. 92-3, Sec. 4.6.2 pp. 94-5, Sec. 4.6.3 p. 96,
  402.     Sec. 16.1 p. 386.
  403.  
  404. 1.31:    This code, straight out of a book, isn't compiling:
  405.  
  406.         int f()
  407.         {
  408.             char a[] = "Hello, world!";
  409.         }
  410.  
  411. A:    Perhaps you have a pre-ANSI compiler, which doesn't allow
  412.     initialization of "automatic aggregates" (i.e. non-static
  413.     local arrays, structures, and unions).  (As a workaround, and
  414.     depending on how the variable a is used, you may be able to make
  415.     it global or static, or replace it with a pointer, or initialize
  416.     it by hand with strcpy() when f() is called.)  See also
  417.     question 11.29.
  418.  
  419. 1.31b:    What's wrong with this initialization?
  420.  
  421.         char *p = malloc(10);
  422.  
  423.     My compiler is complaining about an "invalid initializer",
  424.     or something.
  425.  
  426. A:    Is the declaration of a static or non-local variable?  Function
  427.     calls are allowed only in initializers for automatic variables
  428.     (that is, for local, non-static variables).
  429.  
  430. 1.32:    What is the difference between these initializations?
  431.  
  432.         char a[] = "string literal";
  433.         char *p  = "string literal";
  434.  
  435.     My program crashes if I try to assign a new value to p[i].
  436.  
  437. A:    A string literal can be used in two slightly different ways.  As
  438.     an array initializer (as in the declaration of char a[]), it
  439.     specifies the initial values of the characters in that array.
  440.     Anywhere else, it turns into an unnamed, static array of
  441.     characters, which may be stored in read-only memory, which is
  442.     why you can't safely modify it.  In an expression context, the
  443.     array is converted at once to a pointer, as usual (see section
  444.     6), so the second declaration initializes p to point to the
  445.     unnamed array's first element.
  446.  
  447.     (For compiling old code, some compilers have a switch
  448.     controlling whether strings are writable or not.)
  449.  
  450.     See also questions 1.31, 6.1, 6.2, and 6.8.
  451.  
  452.     References: K&R2 Sec. 5.5 p. 104; ISO Sec. 6.1.4, Sec. 6.5.7;
  453.     Rationale Sec. 3.1.4; H&S Sec. 2.7.4 pp. 31-2.
  454.  
  455. 1.34:    I finally figured out the syntax for declaring pointers to
  456.     functions, but now how do I initialize one?
  457.  
  458. A:    Use something like
  459.  
  460.         extern int func();
  461.         int (*fp)() = func;
  462.  
  463.     When the name of a function appears in an expression like this,
  464.     it "decays" into a pointer (that is, it has its address
  465.     implicitly taken), much as an array name does.
  466.  
  467.     An explicit declaration for the function is normally needed,
  468.     since implicit external function declaration does not happen in
  469.     this case (because the function name in the initialization is
  470.     not part of a function call).
  471.  
  472.     See also questions 1.25 and 4.12.
  473.  
  474.  
  475. Section 2. Structures, Unions, and Enumerations
  476.  
  477. 2.1:    What's the difference between these two declarations?
  478.  
  479.         struct x1 { ... };
  480.         typedef struct { ... } x2;
  481.  
  482. A:    The first form declares a "structure tag"; the second declares a
  483.     "typedef".  The main difference is that you subsequently refer
  484.     to the first type as "struct x1" and the second simply as "x2".
  485.     That is, the second declaration is of a slightly more abstract
  486.     type -- its users don't necessarily know that it is a structure,
  487.     and the keyword struct is not used when declaring instances of it.
  488.  
  489. 2.2:    Why doesn't
  490.  
  491.         struct x { ... };
  492.         x thestruct;
  493.  
  494.     work?
  495.  
  496. A:    C is not C++.  Typedef names are not automatically generated for
  497.     structure tags.  See also question 2.1 above.
  498.  
  499. 2.3:    Can a structure contain a pointer to itself?
  500.  
  501. A:    Most certainly.  See question 1.14.
  502.  
  503. 2.4:    What's the best way of implementing opaque (abstract) data types
  504.     in C?
  505.  
  506. A:    One good way is for clients to use structure pointers (perhaps
  507.     additionally hidden behind typedefs) which point to structure
  508.     types which are not publicly defined.
  509.  
  510. 2.6:    I came across some code that declared a structure like this:
  511.  
  512.         struct name {
  513.             int namelen;
  514.             char namestr[1];
  515.         };
  516.  
  517.     and then did some tricky allocation to make the namestr array
  518.     act like it had several elements.  Is this legal or portable?
  519.  
  520. A:    This technique is popular, although Dennis Ritchie has called it
  521.     "unwarranted chumminess with the C implementation."  An official
  522.     interpretation has deemed that it is not strictly conforming
  523.     with the C Standard, although it does seem to work under all
  524.     known implementations.  (Compilers which check array bounds
  525.     carefully might issue warnings.)
  526.  
  527.     Another possibility is to declare the variable-size element very
  528.     large, rather than very small; in the case of the above example:
  529.  
  530.         ...
  531.         char namestr[MAXSIZE];
  532.  
  533.     where MAXSIZE is larger than any name which will be stored.
  534.     However, it looks like this technique is disallowed by a strict
  535.     interpretation of the Standard as well.  Furthermore, either of
  536.     these "chummy" structures must be used with care, since the
  537.     programmer knows more about their size than the compiler does.
  538.     (In particular, they can generally only be manipulated via
  539.     pointers.)
  540.  
  541.     C9X will introduce the concept of a "flexible array member",
  542.     which will allow the size of an array to be omitted if it is
  543.     the last member in a structure, thus providing a well-defined
  544.     solution.
  545.  
  546.     References: Rationale Sec. 3.5.4.2; C9X Sec. 6.5.2.1.
  547.  
  548. 2.7:    I heard that structures could be assigned to variables and
  549.     passed to and from functions, but K&R1 says not.
  550.  
  551. A:    What K&R1 said (though this was quite some time ago by now) was
  552.     that the restrictions on structure operations would be lifted
  553.     in a forthcoming version of the compiler, and in fact structure
  554.     assignment and passing were fully functional in Ritchie's
  555.     compiler even as K&R1 was being published.  A few ancient C
  556.     compilers may have lacked these operations, but all modern
  557.     compilers support them, and they are part of the ANSI C
  558.     standard, so there should be no reluctance to use them.
  559.  
  560.     (Note that when a structure is assigned, passed, or returned,
  561.     the copying is done monolithically; the data pointed to by any
  562.     pointer fields is *not* copied.)
  563.  
  564.     References: K&R1 Sec. 6.2 p. 121; K&R2 Sec. 6.2 p. 129; ISO
  565.     Sec. 6.1.2.5, Sec. 6.2.2.1, Sec. 6.3.16; H&S Sec. 5.6.2 p. 133.
  566.  
  567. 2.8:    Is there a way to compare structures automatically?
  568.  
  569. A:    No.  There is no single, good way for a compiler to implement
  570.     implicit structure comparison (i.e. to support the == operator
  571.     for structures) which is consistent with C's low-level flavor.
  572.     A simple byte-by-byte comparison could founder on random bits
  573.     present in unused "holes" in the structure (such padding is used
  574.     to keep the alignment of later fields correct; see question
  575.     2.12).  A field-by-field comparison might require unacceptable
  576.     amounts of repetitive code for large structures.
  577.  
  578.     If you need to compare two structures, you'll have to write your
  579.     own function to do so, field by field.
  580.  
  581.     References: K&R2 Sec. 6.2 p. 129; Rationale Sec. 3.3.9; H&S
  582.     Sec. 5.6.2 p. 133.
  583.  
  584. 2.10:    How can I pass constant values to functions which accept
  585.     structure arguments?
  586.  
  587. A:    As of this writing, C has no way of generating anonymous
  588.     structure values.  You will have to use a temporary structure
  589.     variable or a little structure-building function.
  590.  
  591.     The C9X Standard will introduce "compound literals"; one form of
  592.     compound literal will allow structure constants.  For example,
  593.     to pass a constant coordinate pair to a plotpoint() function
  594.     which expects a struct point, you will be able to call
  595.  
  596.         plotpoint((struct point){1, 2});
  597.  
  598.     Combined with "designated initializers" (another C9X feature),
  599.     it will also be possible to specify member values by name:
  600.  
  601.         plotpoint((struct point){.x=1, .y=2});
  602.  
  603.     See also question 4.10.
  604.  
  605.     References: C9X Sec. 6.3.2.5, Sec. 6.5.8.
  606.  
  607. 2.11:    How can I read/write structures from/to data files?
  608.  
  609. A:    It is relatively straightforward to write a structure out using
  610.     fwrite():
  611.  
  612.         fwrite(&somestruct, sizeof somestruct, 1, fp);
  613.  
  614.     and a corresponding fread invocation can read it back in.
  615.     However, data files so written will *not* be portable (see
  616.     questions 2.12 and 20.5).  Note also that if the structure
  617.     contains any pointers, only the pointer values will be written,
  618.     and they are most unlikely to be valid when read back in.
  619.     Finally, note that for widespread portability you must use the
  620.     "b" flag when fopening the files; see question 12.38.
  621.  
  622.     A more portable solution, though it's a bit more work initially,
  623.     is to write a pair of functions for writing and reading a
  624.     structure, field-by-field, in a portable (perhaps even human-
  625.     readable) way.
  626.  
  627.     References: H&S Sec. 15.13 p. 381.
  628.  
  629. 2.12:    My compiler is leaving holes in structures, which is wasting
  630.     space and preventing "binary" I/O to external data files.  Can I
  631.     turn off the padding, or otherwise control the alignment of
  632.     structure fields?
  633.  
  634. A:    Your compiler may provide an extension to give you this control
  635.     (perhaps a #pragma; see question 11.20), but there is no
  636.     standard method.
  637.  
  638.     See also question 20.5.
  639.  
  640.     References: K&R2 Sec. 6.4 p. 138; H&S Sec. 5.6.4 p. 135.
  641.  
  642. 2.13:    Why does sizeof report a larger size than I expect for a
  643.     structure type, as if there were padding at the end?
  644.  
  645. A:    Structures may have this padding (as well as internal padding),
  646.     if necessary, to ensure that alignment properties will be
  647.     preserved when an array of contiguous structures is allocated.
  648.     Even when the structure is not part of an array, the end padding
  649.     remains, so that sizeof can always return a consistent size.
  650.     See also question 2.12 above.
  651.  
  652.     References: H&S Sec. 5.6.7 pp. 139-40.
  653.  
  654. 2.14:    How can I determine the byte offset of a field within a
  655.     structure?
  656.  
  657. A:    ANSI C defines the offsetof() macro, which should be used if
  658.     available; see <stddef.h>.  If you don't have it, one possible
  659.     implementation is
  660.  
  661.         #define offsetof(type, mem) ((size_t) \
  662.             ((char *)&((type *)0)->mem - (char *)(type *)0))
  663.  
  664.     This implementation is not 100% portable; some compilers may
  665.     legitimately refuse to accept it.
  666.  
  667.     See question 2.15 below for a usage hint.
  668.  
  669.     References: ISO Sec. 7.1.6; Rationale Sec. 3.5.4.2; H&S
  670.     Sec. 11.1 pp. 292-3.
  671.  
  672. 2.15:    How can I access structure fields by name at run time?
  673.  
  674. A:    Build a table of names and offsets, using the offsetof() macro.
  675.     The offset of field b in struct a is
  676.  
  677.         offsetb = offsetof(struct a, b)
  678.  
  679.     If structp is a pointer to an instance of this structure, and
  680.     field b is an int (with offset as computed above), b's value can
  681.     be set indirectly with
  682.  
  683.         *(int *)((char *)structp + offsetb) = value;
  684.  
  685. 2.18:    This program works correctly, but it dumps core after it
  686.     finishes.  Why?
  687.  
  688.         struct list {
  689.             char *item;
  690.             struct list *next;
  691.         }
  692.  
  693.         /* Here is the main program. */
  694.  
  695.         main(argc, argv)
  696.         { ... }
  697.  
  698. A:    A missing semicolon causes main() to be declared as returning a
  699.     structure.  (The connection is hard to see because of the
  700.     intervening comment.)  Since structure-valued functions are
  701.     usually implemented by adding a hidden return pointer, the
  702.     generated code for main() tries to accept three arguments,
  703.     although only two are passed (in this case, by the C start-up
  704.     code).  See also questions 10.9 and 16.4.
  705.  
  706.     References: CT&P Sec. 2.3 pp. 21-2.
  707.  
  708. 2.20:    Can I initialize unions?
  709.  
  710. A:    The current C Standard allows an initializer for the first-named
  711.     member of a union.  C9X will introduce "designated initializers"
  712.     which can be used to initialize any member.
  713.  
  714.     References: K&R2 Sec. 6.8 pp. 148-9; ISO Sec. 6.5.7; C9X
  715.     Sec. 6.5.8; H&S Sec. 4.6.7 p. 100.
  716.  
  717. 2.22:    What is the difference between an enumeration and a set of
  718.     preprocessor #defines?
  719.  
  720. A:    At the present time, there is little difference.  The C Standard
  721.     says that enumerations may be freely intermixed with other
  722.     integral types, without errors.  (If, on the other hand, such
  723.     intermixing were disallowed without explicit casts, judicious
  724.     use of enumerations could catch certain programming errors.)
  725.  
  726.     Some advantages of enumerations are that the numeric values are
  727.     automatically assigned, that a debugger may be able to display
  728.     the symbolic values when enumeration variables are examined, and
  729.     that they obey block scope.  (A compiler may also generate
  730.     nonfatal warnings when enumerations and integers are
  731.     indiscriminately mixed, since doing so can still be considered
  732.     bad style even though it is not strictly illegal.)  A
  733.     disadvantage is that the programmer has little control over
  734.     those nonfatal warnings; some programmers also resent not having
  735.     control over the sizes of enumeration variables.
  736.  
  737.     References: K&R2 Sec. 2.3 p. 39, Sec. A4.2 p. 196; ISO
  738.     Sec. 6.1.2.5, Sec. 6.5.2, Sec. 6.5.2.2, Annex F; H&S Sec. 5.5
  739.     pp. 127-9, Sec. 5.11.2 p. 153.
  740.  
  741. 2.24:    Is there an easy way to print enumeration values symbolically?
  742.  
  743. A:    No.  You can write a little function to map an enumeration
  744.     constant to a string.  (For debugging purposes, a good debugger
  745.     should automatically print enumeration constants symbolically.)
  746.  
  747.  
  748. Section 3. Expressions
  749.  
  750. 3.1:    Why doesn't this code:
  751.  
  752.         a[i] = i++;
  753.  
  754.     work?
  755.  
  756. A:    The subexpression i++ causes a side effect -- it modifies i's
  757.     value -- which leads to undefined behavior since i is also
  758.     referenced elsewhere in the same expression, and there's no way
  759.     to determine whether the reference (in a[i] on the left-hand
  760.     side) should be to the old or the new value.  (Note that
  761.     although the language in K&R suggests that the behavior of this
  762.     expression is unspecified, the C Standard makes the stronger
  763.     statement that it is undefined -- see question 11.33.)
  764.  
  765.     References: K&R1 Sec. 2.12; K&R2 Sec. 2.12; ISO Sec. 6.3; H&S
  766.     Sec. 7.12 pp. 227-9.
  767.  
  768. 3.2:    Under my compiler, the code
  769.  
  770.         int i = 7;
  771.         printf("%d\n", i++ * i++);
  772.  
  773.     prints 49.  Regardless of the order of evaluation, shouldn't it
  774.     print 56?
  775.  
  776. A:    Although the postincrement and postdecrement operators ++ and --
  777.     perform their operations after yielding the former value, the
  778.     implication of "after" is often misunderstood.  It is *not*
  779.     guaranteed that an increment or decrement is performed
  780.     immediately after giving up the previous value and before any
  781.     other part of the expression is evaluated.  It is merely
  782.     guaranteed that the update will be performed sometime before the
  783.     expression is considered "finished" (before the next "sequence
  784.     point," in ANSI C's terminology; see question 3.8).  In the
  785.     example, the compiler chose to multiply the previous value by
  786.     itself and to perform both increments afterwards.
  787.  
  788.     The behavior of code which contains multiple, ambiguous side
  789.     effects has always been undefined.  (Loosely speaking, by
  790.     "multiple, ambiguous side effects" we mean any combination of
  791.     ++, --, =, +=, -=, etc. in a single expression which causes the
  792.     same object either to be modified twice or modified and then
  793.     inspected.  This is a rough definition; see question 3.8 for a
  794.     precise one, and question 11.33 for the meaning of "undefined.")
  795.     Don't even try to find out how your compiler implements such
  796.     things (contrary to the ill-advised exercises in many C
  797.     textbooks); as K&R wisely point out, "if you don't know *how*
  798.     they are done on various machines, that innocence may help to
  799.     protect you."
  800.  
  801.     References: K&R1 Sec. 2.12 p. 50; K&R2 Sec. 2.12 p. 54; ISO
  802.     Sec. 6.3; H&S Sec. 7.12 pp. 227-9; CT&P Sec. 3.7 p. 47; PCS
  803.     Sec. 9.5 pp. 120-1.
  804.  
  805. 3.3:    I've experimented with the code
  806.  
  807.         int i = 3;
  808.         i = i++;
  809.  
  810.     on several compilers.  Some gave i the value 3, and some gave 4.
  811.     Which compiler is correct?
  812.  
  813. A:    There is no correct answer; the expression is undefined.  See
  814.     questions 3.1, 3.8, 3.9, and 11.33.  (Also, note that neither
  815.     i++ nor ++i is the same as i+1.  If you want to increment i,
  816.     use i=i+1, i+=1, i++, or ++i, not some combination.  See also
  817.     question 3.12.)
  818.  
  819. 3.3b:    Here's a slick expression:
  820.  
  821.         a ^= b ^= a ^= b
  822.  
  823.     It swaps a and b without using a temporary.
  824.  
  825. A:    Not portably, it doesn't.  It attempts to modify the variable a
  826.     twice between sequence points, so its behavior is undefined.
  827.  
  828.     For example, it has been reported that when given the code
  829.  
  830.         int a = 123, b = 7654;
  831.         a ^= b ^= a ^= b;
  832.  
  833.     the SCO Optimizing C compiler (icc) sets b to 123 and a to 0.
  834.  
  835.     See also questions 3.1, 3.8, 10.3, and 20.15c.
  836.  
  837. 3.4:    Can I use explicit parentheses to force the order of evaluation
  838.     I want?  Even if I don't, doesn't precedence dictate it?
  839.  
  840. A:    Not in general.
  841.  
  842.     Operator precedence and explicit parentheses impose only a
  843.     partial ordering on the evaluation of an expression.  In the
  844.     expression
  845.  
  846.         f() + g() * h()
  847.  
  848.     although we know that the multiplication will happen before the
  849.     addition, there is no telling which of the three functions will
  850.     be called first.
  851.  
  852.     When you need to ensure the order of subexpression evaluation,
  853.     you may need to use explicit temporary variables and separate
  854.     statements.
  855.  
  856.     References: K&R1 Sec. 2.12 p. 49, Sec. A.7 p. 185; K&R2
  857.     Sec. 2.12 pp. 52-3, Sec. A.7 p. 200.
  858.  
  859. 3.5:    But what about the && and || operators?
  860.     I see code like "while((c = getchar()) != EOF && c != '\n')" ...
  861.  
  862. A:    There is a special "short-circuiting" exception for those
  863.     operators.  The right-hand side is not evaluated if the left-
  864.     hand side determines the outcome (i.e. is true for || or false
  865.     for &&).  Therefore, left-to-right evaluation is guaranteed, as
  866.     it also is for the comma operator.  Furthermore, all of these
  867.     operators (along with ?:) introduce an extra internal sequence
  868.     point (see question 3.8).
  869.  
  870.     References: K&R1 Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R2
  871.     Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ISO Sec. 6.3.13,
  872.     Sec. 6.3.14, Sec. 6.3.15; H&S Sec. 7.7 pp. 217-8, Sec. 7.8 pp.
  873.     218-20, Sec. 7.12.1 p. 229; CT&P Sec. 3.7 pp. 46-7.
  874.  
  875. 3.8:    How can I understand these complex expressions?  What's a
  876.     "sequence point"?
  877.  
  878. A:    A sequence point is a point in time (at the end of the
  879.     evaluation of a full expression, or at the ||, &&, ?:, or comma
  880.     operators, or just before a function call) at which the dust
  881.     has settled and all side effects are guaranteed to be complete.
  882.     The ANSI/ISO C Standard states that
  883.  
  884.         Between the previous and next sequence point an
  885.         object shall have its stored value modified at
  886.         most once by the evaluation of an expression.
  887.         Furthermore, the prior value shall be accessed
  888.         only to determine the value to be stored.
  889.  
  890.     The second sentence can be difficult to understand.  It says
  891.     that if an object is written to within a full expression, any
  892.     and all accesses to it within the same expression must be for
  893.     the purposes of computing the value to be written.  This rule
  894.     effectively constrains legal expressions to those in which the
  895.     accesses demonstrably precede the modification.
  896.  
  897.     See also question 3.9 below.
  898.  
  899.     References: ISO Sec. 5.1.2.3, Sec. 6.3, Sec. 6.6, Annex C;
  900.     Rationale Sec. 2.1.2.3; H&S Sec. 7.12.1 pp. 228-9.
  901.  
  902. 3.9:    So given
  903.  
  904.         a[i] = i++;
  905.  
  906.     we don't know which cell of a[] gets written to, but i does get
  907.     incremented by one, right?
  908.  
  909. A:    *No*.  Once an expression or program becomes undefined, *all*
  910.     aspects of it become undefined.  See questions 3.2, 3.3, 11.33,
  911.     and 11.35.
  912.  
  913. 3.12:    If I'm not using the value of the expression, should I use i++
  914.     or ++i to increment a variable?
  915.  
  916. A:    Since the two forms differ only in the value yielded, they are
  917.     entirely equivalent when only their side effect is needed.
  918.     (However, the prefix form is preferred in C++.)  See also
  919.     question 3.3.
  920.  
  921.     References: K&R1 Sec. 2.8 p. 43; K&R2 Sec. 2.8 p. 47; ISO
  922.     Sec. 6.3.2.4, Sec. 6.3.3.1; H&S Sec. 7.4.4 pp. 192-3, Sec. 7.5.8
  923.     pp. 199-200.
  924.  
  925. 3.14:    Why doesn't the code
  926.  
  927.         int a = 1000, b = 1000;
  928.         long int c = a * b;
  929.  
  930.     work?
  931.  
  932. A:    Under C's integral promotion rules, the multiplication is
  933.     carried out using int arithmetic, and the result may overflow or
  934.     be truncated before being promoted and assigned to the long int
  935.     left-hand side.  Use an explicit cast to force long arithmetic:
  936.  
  937.         long int c = (long int)a * b;
  938.  
  939.     Note that (long int)(a * b) would *not* have the desired effect.
  940.  
  941.     A similar problem can arise when two integers are divided, with
  942.     the result assigned to a floating-point variable; the solution
  943.     is similar, too.
  944.  
  945.     References: K&R1 Sec. 2.7 p. 41; K&R2 Sec. 2.7 p. 44; ISO
  946.     Sec. 6.2.1.5; H&S Sec. 6.3.4 p. 176; CT&P Sec. 3.9 pp. 49-50.
  947.  
  948. 3.16:    I have a complicated expression which I have to assign to one of
  949.     two variables, depending on a condition.  Can I use code like
  950.     this?
  951.  
  952.         ((condition) ? a : b) = complicated_expression;
  953.  
  954. A:    No.  The ?: operator, like most operators, yields a value, and
  955.     you can't assign to a value.  (In other words, ?: does not yield
  956.     an "lvalue".)  If you really want to, you can try something like
  957.  
  958.         *((condition) ? &a : &b) = complicated_expression;
  959.  
  960.     although this is admittedly not as pretty.
  961.  
  962.     References: ISO Sec. 6.3.15; H&S Sec. 7.1 pp. 179-180.
  963.  
  964.  
  965. Section 4. Pointers
  966.  
  967. 4.2:    I'm trying to declare a pointer and allocate some space for it,
  968.     but it's not working.  What's wrong with this code?
  969.  
  970.         char *p;
  971.         *p = malloc(10);
  972.  
  973. A:    The pointer you declared is p, not *p.  To make a pointer point
  974.     somewhere, you just use the name of the pointer:
  975.  
  976.         p = malloc(10);
  977.  
  978.     It's when you're manipulating the pointed-to memory that you use
  979.     * as an indirection operator:
  980.  
  981.         *p = 'H';
  982.  
  983.     See also questions 1.21, 7.1, 7.3c, and 8.3.
  984.  
  985.     References: CT&P Sec. 3.1 p. 28.
  986.  
  987. 4.3:    Does *p++ increment p, or what it points to?
  988.  
  989. A:    Postfix ++ essentially has higher precedence than the prefix
  990.     unary operators.  Therefore, *p++ is equivalent to *(p++); it
  991.     increments p, and returns the value which p pointed to before p
  992.     was incremented.  To increment the value pointed to by p, use
  993.     (*p)++ (or perhaps ++*p, if the order of the side effect doesn't
  994.     matter).
  995.  
  996.     References: K&R1 Sec. 5.1 p. 91; K&R2 Sec. 5.1 p. 95; ISO
  997.     Sec. 6.3.2, Sec. 6.3.3; H&S Sec. 7.4.4 pp. 192-3, Sec. 7.5 p.
  998.     193, Secs. 7.5.7,7.5.8 pp. 199-200.
  999.  
  1000. 4.5:    I have a char * pointer that happens to point to some ints, and
  1001.     I want to step it over them.  Why doesn't
  1002.  
  1003.         ((int *)p)++;
  1004.  
  1005.     work?
  1006.  
  1007. A:    In C, a cast operator does not mean "pretend these bits have a
  1008.     different type, and treat them accordingly"; it is a conversion
  1009.     operator, and by definition it yields an rvalue, which cannot be
  1010.     assigned to, or incremented with ++.  (It is either an accident
  1011.     or a delibrate but nonstandard extension if a particular
  1012.     compiler accepts expressions such as the above.)  Say what you
  1013.     mean: use
  1014.  
  1015.         p = (char *)((int *)p + 1);
  1016.  
  1017.     or (since p is a char *) simply
  1018.  
  1019.         p += sizeof(int);
  1020.  
  1021.     Whenever possible, you should choose appropriate pointer types
  1022.     in the first place, instead of trying to treat one type as
  1023.     another.
  1024.  
  1025.     References: K&R2 Sec. A7.5 p. 205; ISO Sec. 6.3.4; Rationale
  1026.     Sec. 3.3.2.4; H&S Sec. 7.1 pp. 179-80.
  1027.  
  1028. 4.8:    I have a function which accepts, and is supposed to initialize,
  1029.     a pointer:
  1030.  
  1031.         void f(int *ip)
  1032.         {
  1033.             static int dummy = 5;
  1034.             ip = &dummy;
  1035.         }
  1036.  
  1037.     But when I call it like this:
  1038.  
  1039.         int *ip;
  1040.         f(ip);
  1041.  
  1042.     the pointer in the caller remains unchanged.
  1043.  
  1044. A:    Are you sure the function initialized what you thought it did?
  1045.     Remember that arguments in C are passed by value.  The called
  1046.     function altered only the passed copy of the pointer.  You'll
  1047.     either want to pass the address of the pointer (the function
  1048.     will end up accepting a pointer-to-a-pointer), or have the
  1049.     function return the pointer.
  1050.  
  1051.     See also questions 4.9 and 4.11.
  1052.  
  1053. 4.9:    Can I use a void ** pointer as a parameter so that a function
  1054.     can accept a generic pointer by reference?
  1055.  
  1056. A:    Not portably.  There is no generic pointer-to-pointer type in C.
  1057.     void * acts as a generic pointer only because conversions are
  1058.     applied automatically when other pointer types are assigned to
  1059.     and from void *'s; these conversions cannot be performed (the
  1060.     correct underlying pointer type is not known) if an attempt is
  1061.     made to indirect upon a void ** value which points at a pointer
  1062.     type other than void *.
  1063.  
  1064. 4.10:    I have a function
  1065.  
  1066.         extern int f(int *);
  1067.  
  1068.     which accepts a pointer to an int.  How can I pass a constant by
  1069.     reference?  A call like
  1070.  
  1071.         f(&5);
  1072.  
  1073.     doesn't seem to work.
  1074.  
  1075. A:    You can't do this directly.  You will have to declare a
  1076.     temporary variable, and then pass its address to the function:
  1077.  
  1078.         int five = 5;
  1079.         f(&five);
  1080.  
  1081.     See also questions 2.10, 4.8, and 20.1.
  1082.  
  1083. 4.11:    Does C even have "pass by reference"?
  1084.  
  1085. A:    Not really.  Strictly speaking, C always uses pass by value.
  1086.     You can simulate pass by reference yourself, by defining
  1087.     functions which accept pointers and then using the & operator
  1088.     when calling, and the compiler will essentially simulate it for
  1089.     you when you pass an array to a function (by passing a pointer
  1090.     instead, see question 6.4 et al.).  However, C has nothing truly
  1091.     equivalent to formal pass by reference or C++ reference
  1092.     parameters.  (On the other hand, function-like preprocessor
  1093.     macros can provide a form of "pass by name".)
  1094.  
  1095.     See also questions 4.8 and 20.1.
  1096.  
  1097.     References: K&R1 Sec. 1.8 pp. 24-5, Sec. 5.2 pp. 91-3; K&R2
  1098.     Sec. 1.8 pp. 27-8, Sec. 5.2 pp. 95-7; ISO Sec. 6.3.2.2; H&S
  1099.     Sec. 9.5 pp. 273-4.
  1100.  
  1101. 4.12:    I've seen different methods used for calling functions via
  1102.     pointers.  What's the story?
  1103.  
  1104. A:    Originally, a pointer to a function had to be "turned into" a
  1105.     "real" function, with the * operator (and an extra pair of
  1106.     parentheses, to keep the precedence straight), before calling:
  1107.  
  1108.         int r, func(), (*fp)() = func;
  1109.         r = (*fp)();
  1110.  
  1111.     It can also be argued that functions are always called via
  1112.     pointers, and that "real" function names always decay implicitly
  1113.     into pointers (in expressions, as they do in initializations;
  1114.     see question 1.34).  This reasoning (which is in fact used in
  1115.     the ANSI standard) means that
  1116.  
  1117.         r = fp();
  1118.  
  1119.     is legal and works correctly, whether fp is the name of a
  1120.     function or a pointer to one.  (The usage has always been
  1121.     unambiguous; there is nothing you ever could have done with a
  1122.     function pointer followed by an argument list except call the
  1123.     function pointed to.)  An explicit * is still allowed.
  1124.  
  1125.     See also question 1.34.
  1126.  
  1127.     References: K&R1 Sec. 5.12 p. 116; K&R2 Sec. 5.11 p. 120; ISO
  1128.     Sec. 6.3.2.2; Rationale Sec. 3.3.2.2; H&S Sec. 5.8 p. 147,
  1129.     Sec. 7.4.3 p. 190.
  1130.  
  1131.  
  1132. Section 5. Null Pointers
  1133.  
  1134. 5.1:    What is this infamous null pointer, anyway?
  1135.  
  1136. A:    The language definition states that for each pointer type, there
  1137.     is a special value -- the "null pointer" -- which is
  1138.     distinguishable from all other pointer values and which is
  1139.     "guaranteed to compare unequal to a pointer to any object or
  1140.     function."  That is, the address-of operator & will never yield
  1141.     a null pointer, nor will a successful call to malloc().
  1142.     (malloc() does return a null pointer when it fails, and this is
  1143.     a typical use of null pointers: as a "special" pointer value
  1144.     with some other meaning, usually "not allocated" or "not
  1145.     pointing anywhere yet.")
  1146.  
  1147.     A null pointer is conceptually different from an uninitialized
  1148.     pointer.  A null pointer is known not to point to any object or
  1149.     function; an uninitialized pointer might point anywhere.  See
  1150.     also questions 1.30, 7.1, and 7.31.
  1151.  
  1152.     As mentioned above, there is a null pointer for each pointer
  1153.     type, and the internal values of null pointers for different
  1154.     types may be different.  Although programmers need not know the
  1155.     internal values, the compiler must always be informed which type
  1156.     of null pointer is required, so that it can make the distinction
  1157.     if necessary (see questions 5.2, 5.5, and 5.6 below).
  1158.  
  1159.     References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ISO
  1160.     Sec. 6.2.2.3; Rationale Sec. 3.2.2.3; H&S Sec. 5.3.2 pp. 121-3.
  1161.  
  1162. 5.2:    How do I get a null pointer in my programs?
  1163.  
  1164. A:    According to the language definition, a constant 0 in a pointer
  1165.     context is converted into a null pointer at compile time.  That
  1166.     is, in an initialization, assignment, or comparison when one
  1167.     side is a variable or expression of pointer type, the compiler
  1168.     can tell that a constant 0 on the other side requests a null
  1169.     pointer, and generate the correctly-typed null pointer value.
  1170.     Therefore, the following fragments are perfectly legal:
  1171.  
  1172.         char *p = 0;
  1173.         if(p != 0)
  1174.  
  1175.     (See also question 5.3.)
  1176.  
  1177.     However, an argument being passed to a function is not
  1178.     necessarily recognizable as a pointer context, and the compiler
  1179.     may not be able to tell that an unadorned 0 "means" a null
  1180.     pointer.  To generate a null pointer in a function call context,
  1181.     an explicit cast may be required, to force the 0 to be
  1182.     recognized as a pointer.  For example, the Unix system call
  1183.     execl takes a variable-length, null-pointer-terminated list of
  1184.     character pointer arguments, and is correctly called like this:
  1185.  
  1186.         execl("/bin/sh", "sh", "-c", "date", (char *)0);
  1187.  
  1188.     If the (char *) cast on the last argument were omitted, the
  1189.     compiler would not know to pass a null pointer, and would pass
  1190.     an integer 0 instead.  (Note that many Unix manuals get this
  1191.     example wrong.)
  1192.  
  1193.     When function prototypes are in scope, argument passing becomes
  1194.     an "assignment context," and most casts may safely be omitted,
  1195.     since the prototype tells the compiler that a pointer is
  1196.     required, and of which type, enabling it to correctly convert an
  1197.     unadorned 0.  Function prototypes cannot provide the types for
  1198.     variable arguments in variable-length argument lists however, so
  1199.     explicit casts are still required for those arguments.  (See
  1200.     also question 15.3.)  It is probably safest to properly cast
  1201.     all null pointer constants in function calls, to guard against
  1202.     varargs functions or those without prototypes.
  1203.  
  1204.     Summary:
  1205.  
  1206.         Unadorned 0 okay:    Explicit cast required:
  1207.  
  1208.         initialization        function call,
  1209.                     no prototype in scope
  1210.         assignment
  1211.                     variable argument in
  1212.         comparison        varargs function call
  1213.  
  1214.         function call,
  1215.         prototype in scope,
  1216.         fixed argument
  1217.  
  1218.     References: K&R1 Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R2
  1219.     Sec. A7.10 p. 207, Sec. A7.17 p. 209; ISO Sec. 6.2.2.3; H&S
  1220.     Sec. 4.6.3 p. 95, Sec. 6.2.7 p. 171.
  1221.  
  1222. 5.3:    Is the abbreviated pointer comparison "if(p)" to test for non-
  1223.     null pointers valid?  What if the internal representation for
  1224.     null pointers is nonzero?
  1225.  
  1226. A:    When C requires the Boolean value of an expression, a false
  1227.     value is inferred when the expression compares equal to zero,
  1228.     and a true value otherwise.  That is, whenever one writes
  1229.  
  1230.         if(expr)
  1231.  
  1232.     where "expr" is any expression at all, the compiler essentially
  1233.     acts as if it had been written as
  1234.  
  1235.         if((expr) != 0)
  1236.  
  1237.     Substituting the trivial pointer expression "p" for "expr", we
  1238.     have
  1239.  
  1240.         if(p)    is equivalent to        if(p != 0)
  1241.  
  1242.     and this is a comparison context, so the compiler can tell that
  1243.     the (implicit) 0 is actually a null pointer constant, and use
  1244.     the correct null pointer value.  There is no trickery involved
  1245.     here; compilers do work this way, and generate identical code
  1246.     for both constructs.  The internal representation of a null
  1247.     pointer does *not* matter.
  1248.  
  1249.     The boolean negation operator, !, can be described as follows:
  1250.  
  1251.         !expr    is essentially equivalent to    (expr)?0:1
  1252.             or to                ((expr) == 0)
  1253.  
  1254.     which leads to the conclusion that
  1255.  
  1256.         if(!p)    is equivalent to        if(p == 0)
  1257.  
  1258.     "Abbreviations" such as if(p), though perfectly legal, are
  1259.     considered by some to be bad style (and by others to be good
  1260.     style; see question 17.10).
  1261.  
  1262.     See also question 9.2.
  1263.  
  1264.     References: K&R2 Sec. A7.4.7 p. 204; ISO Sec. 6.3.3.3,
  1265.     Sec. 6.3.9, Sec. 6.3.13, Sec. 6.3.14, Sec. 6.3.15, Sec. 6.6.4.1,
  1266.     Sec. 6.6.5; H&S Sec. 5.3.2 p. 122.
  1267.  
  1268. 5.4:    What is NULL and how is it #defined?
  1269.  
  1270. A:    As a matter of style, many programmers prefer not to have
  1271.     unadorned 0's scattered through their programs.  Therefore, the
  1272.     preprocessor macro NULL is #defined (by <stdio.h> and several
  1273.     other headers) with the value 0, possibly cast to (void *) (see
  1274.     also question 5.6).  A programmer who wishes to make explicit
  1275.     the distinction between 0 the integer and 0 the null pointer
  1276.     constant can then use NULL whenever a null pointer is required.
  1277.  
  1278.     Using NULL is a stylistic convention only; the preprocessor
  1279.     turns NULL back into 0 which is then recognized by the compiler,
  1280.     in pointer contexts, as before.  In particular, a cast may still
  1281.     be necessary before NULL (as before 0) in a function call
  1282.     argument.  The table under question 5.2 above applies for NULL
  1283.     as well as 0 (an unadorned NULL is equivalent to an unadorned
  1284.     0).
  1285.  
  1286.     NULL should *only* be used for pointers; see question 5.9.
  1287.  
  1288.     References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ISO
  1289.     Sec. 7.1.6, Sec. 6.2.2.3; Rationale Sec. 4.1.5; H&S Sec. 5.3.2
  1290.     p. 122, Sec. 11.1 p. 292.
  1291.  
  1292. 5.5:    How should NULL be defined on a machine which uses a nonzero bit
  1293.     pattern as the internal representation of a null pointer?
  1294.  
  1295. A:    The same as on any other machine: as 0 (or some version of 0;
  1296.     see question 5.4).
  1297.  
  1298.     Whenever a programmer requests a null pointer, either by writing
  1299.     "0" or "NULL", it is the compiler's responsibility to generate
  1300.     whatever bit pattern the machine uses for that null pointer.
  1301.     Therefore, #defining NULL as 0 on a machine for which internal
  1302.     null pointers are nonzero is as valid as on any other: the
  1303.     compiler must always be able to generate the machine's correct
  1304.     null pointers in response to unadorned 0's seen in pointer
  1305.     contexts.  See also questions 5.2, 5.10, and 5.17.
  1306.  
  1307.     References: ISO Sec. 7.1.6; Rationale Sec. 4.1.5.
  1308.  
  1309. 5.6:    If NULL were defined as follows:
  1310.  
  1311.         #define NULL ((char *)0)
  1312.  
  1313.     wouldn't that make function calls which pass an uncast NULL
  1314.     work?
  1315.  
  1316. A:    Not in general.  The complication is that there are machines
  1317.     which use different internal representations for pointers to
  1318.     different types of data.  The suggested definition would make
  1319.     uncast NULL arguments to functions expecting pointers to
  1320.     characters work correctly, but pointer arguments of other types
  1321.     would still be problematical, and legal constructions such as
  1322.  
  1323.         FILE *fp = NULL;
  1324.  
  1325.     could fail.
  1326.  
  1327.     Nevertheless, ANSI C allows the alternate definition
  1328.  
  1329.         #define NULL ((void *)0)
  1330.  
  1331.     for NULL.  Besides potentially helping incorrect programs to
  1332.     work (but only on machines with homogeneous pointers, thus
  1333.     questionably valid assistance), this definition may catch
  1334.     programs which use NULL incorrectly (e.g. when the ASCII NUL
  1335.     character was really intended; see question 5.9).
  1336.  
  1337.     References: Rationale Sec. 4.1.5.
  1338.  
  1339. 5.9:    If NULL and 0 are equivalent as null pointer constants, which
  1340.     should I use?
  1341.  
  1342. A:    Many programmers believe that NULL should be used in all pointer
  1343.     contexts, as a reminder that the value is to be thought of as a
  1344.     pointer.  Others feel that the confusion surrounding NULL and 0
  1345.     is only compounded by hiding 0 behind a macro, and prefer to use
  1346.     unadorned 0 instead.  There is no one right answer.  (See also
  1347.     questions 9.2 and 17.10.)  C programmers must understand that
  1348.     NULL and 0 are interchangeable in pointer contexts, and that an
  1349.     uncast 0 is perfectly acceptable.  Any usage of NULL (as opposed
  1350.     to 0) should be considered a gentle reminder that a pointer is
  1351.     involved; programmers should not depend on it (either for their
  1352.     own understanding or the compiler's) for distinguishing pointer
  1353.     0's from integer 0's.
  1354.  
  1355.     NULL should *not* be used when another kind of 0 is required,
  1356.     even though it might work, because doing so sends the wrong
  1357.     stylistic message.  (Furthermore, ANSI allows the definition of
  1358.     NULL to be ((void *)0), which will not work at all in non-
  1359.     pointer contexts.)  In particular, do not use NULL when the
  1360.     ASCII null character (NUL) is desired.  Provide your own
  1361.     definition
  1362.  
  1363.         #define NUL '\0'
  1364.  
  1365.     if you must.
  1366.  
  1367.     References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102.
  1368.  
  1369. 5.10:    But wouldn't it be better to use NULL (rather than 0), in case
  1370.     the value of NULL changes, perhaps on a machine with nonzero
  1371.     internal null pointers?
  1372.  
  1373. A:    No.  (Using NULL may be preferable, but not for this reason.)
  1374.     Although symbolic constants are often used in place of numbers
  1375.     because the numbers might change, this is *not* the reason that
  1376.     NULL is used in place of 0.  Once again, the language guarantees
  1377.     that source-code 0's (in pointer contexts) generate null
  1378.     pointers.  NULL is used only as a stylistic convention.  See
  1379.     questions 5.5 and 9.2.
  1380.  
  1381. 5.12:    I use the preprocessor macro
  1382.  
  1383.         #define Nullptr(type) (type *)0
  1384.  
  1385.     to help me build null pointers of the correct type.
  1386.  
  1387. A:    This trick, though popular and superficially attractive, does
  1388.     not buy much.  It is not needed in assignments or comparisons;
  1389.     see question 5.2.  (It does not even save keystrokes.)  See also
  1390.     questions 9.1 and 10.2.
  1391.  
  1392. 5.13:    This is strange.  NULL is guaranteed to be 0, but the null
  1393.     pointer is not?
  1394.  
  1395. A:    When the term "null" or "NULL" is casually used, one of several
  1396.     things may be meant:
  1397.  
  1398.     1.    The conceptual null pointer, the abstract language concept
  1399.         defined in question 5.1.  It is implemented with...
  1400.  
  1401.     2.    The internal (or run-time) representation of a null
  1402.         pointer, which may or may not be all-bits-0 and which may
  1403.         be different for different pointer types.  The actual
  1404.         values should be of concern only to compiler writers.
  1405.         Authors of C programs never see them, since they use...
  1406.  
  1407.     3.    The null pointer constant, which is a constant integer 0
  1408.         (see question 5.2).  It is often hidden behind...
  1409.  
  1410.     4.    The NULL macro, which is #defined to be 0 (see question
  1411.         5.4).  Finally, as red herrings, we have...
  1412.  
  1413.     5.    The ASCII null character (NUL), which does have all bits
  1414.         zero, but has no necessary relation to the null pointer
  1415.         except in name; and...
  1416.  
  1417.     6.    The "null string," which is another name for the empty
  1418.         string ("").  Using the term "null string" can be
  1419.         confusing in C, because an empty string involves a null
  1420.         ('\0') character, but *not* a null pointer, which brings
  1421.         us full circle...
  1422.  
  1423.     This article uses the phrase "null pointer" (in lower case) for
  1424.     sense 1, the character "0" or the phrase "null pointer constant"
  1425.     for sense 3, and the capitalized word "NULL" for sense 4.
  1426.  
  1427. 5.14:    Why is there so much confusion surrounding null pointers?  Why
  1428.     do these questions come up so often?
  1429.  
  1430. A:    C programmers traditionally like to know more than they might
  1431.     need to about the underlying machine implementation.  The fact
  1432.     that null pointers are represented both in source code, and
  1433.     internally to most machines, as zero invites unwarranted
  1434.     assumptions.  The use of a preprocessor macro (NULL) may seem
  1435.     to suggest that the value could change some day, or on some
  1436.     weird machine.  The construct "if(p == 0)" is easily misread
  1437.     as calling for conversion of p to an integral type, rather
  1438.     than 0 to a pointer type, before the comparison.  Finally,
  1439.     the distinction between the several uses of the term "null"
  1440.     (listed in question 5.13 above) is often overlooked.
  1441.  
  1442.     One good way to wade out of the confusion is to imagine that C
  1443.     used a keyword (perhaps "nil", like Pascal) as a null pointer
  1444.     constant.  The compiler could either turn "nil" into the
  1445.     appropriate type of null pointer when it could unambiguously
  1446.     determine that type from the source code, or complain when it
  1447.     could not.  Now in fact, in C the keyword for a null pointer
  1448.     constant is not "nil" but "0", which works almost as well,
  1449.     except that an uncast "0" in a non-pointer context generates an
  1450.     integer zero instead of an error message, and if that uncast 0
  1451.     was supposed to be a null pointer constant, the code may not
  1452.     work.
  1453.  
  1454. 5.15:    I'm confused.  I just can't understand all this null pointer
  1455.     stuff.
  1456.  
  1457. A:    Here are two simple rules you can follow:
  1458.  
  1459.     1.    When you want a null pointer constant in source code,
  1460.         use "0" or "NULL".
  1461.  
  1462.     2.    If the usage of "0" or "NULL" is an argument in a
  1463.         function call, cast it to the pointer type expected by
  1464.         the function being called.
  1465.  
  1466.     The rest of the discussion has to do with other people's
  1467.     misunderstandings, with the internal representation of null
  1468.     pointers (which you shouldn't need to know), and with the
  1469.     complexities of function prototypes.  (Taking those complexities
  1470.     into account, we find that rule 2 is conservative, of course;
  1471.     but it doesn't hurt.)  Understand questions 5.1, 5.2, and 5.4,
  1472.     and consider 5.3, 5.9, 5.13, and 5.14, and you'll do fine.
  1473.  
  1474. 5.16:    Given all the confusion surrounding null pointers, wouldn't it
  1475.     be easier simply to require them to be represented internally by
  1476.     zeroes?
  1477.  
  1478. A:    If for no other reason, doing so would be ill-advised because it
  1479.     would unnecessarily constrain implementations which would
  1480.     otherwise naturally represent null pointers by special, nonzero
  1481.     bit patterns, particularly when those values would trigger
  1482.     automatic hardware traps for invalid accesses.
  1483.  
  1484.     Besides, what would such a requirement really accomplish?
  1485.     Proper understanding of null pointers does not require knowledge
  1486.     of the internal representation, whether zero or nonzero.
  1487.     Assuming that null pointers are internally zero does not make
  1488.     any code easier to write (except for a certain ill-advised usage
  1489.     of calloc(); see question 7.31).  Known-zero internal pointers
  1490.     would not obviate casts in function calls, because the *size* of
  1491.     the pointer might still be different from that of an int.  (If
  1492.     "nil" were used to request null pointers, as mentioned in
  1493.     question 5.14 above, the urge to assume an internal zero
  1494.     representation would not even arise.)
  1495.  
  1496. 5.17:    Seriously, have any actual machines really used nonzero null
  1497.     pointers, or different representations for pointers to different
  1498.     types?
  1499.  
  1500. A:    The Prime 50 series used segment 07777, offset 0 for the null
  1501.     pointer, at least for PL/I.  Later models used segment 0, offset
  1502.     0 for null pointers in C, necessitating new instructions such as
  1503.     TCNP (Test C Null Pointer), evidently as a sop to all the extant
  1504.     poorly-written C code which made incorrect assumptions.  Older,
  1505.     word-addressed Prime machines were also notorious for requiring
  1506.     larger byte pointers (char *'s) than word pointers (int *'s).
  1507.  
  1508.     The Eclipse MV series from Data General has three
  1509.     architecturally supported pointer formats (word, byte, and bit
  1510.     pointers), two of which are used by C compilers: byte pointers
  1511.     for char * and void *, and word pointers for everything else.
  1512.  
  1513.     Some Honeywell-Bull mainframes use the bit pattern 06000 for
  1514.     (internal) null pointers.
  1515.  
  1516.     The CDC Cyber 180 Series has 48-bit pointers consisting of a
  1517.     ring, segment, and offset.  Most users (in ring 11) have null
  1518.     pointers of 0xB00000000000.  It was common on old CDC ones-
  1519.     complement machines to use an all-one-bits word as a special
  1520.     flag for all kinds of data, including invalid addresses.
  1521.  
  1522.     The old HP 3000 series uses a different addressing scheme for
  1523.     byte addresses than for word addresses; like several of the
  1524.     machines above it therefore uses different representations for
  1525.     char * and void * pointers than for other pointers.
  1526.  
  1527.     The Symbolics Lisp Machine, a tagged architecture, does not even
  1528.     have conventional numeric pointers; it uses the pair <NIL, 0>
  1529.     (basically a nonexistent <object, offset> handle) as a C null
  1530.     pointer.
  1531.  
  1532.     Depending on the "memory model" in use, 8086-family processors
  1533.     (PC compatibles) may use 16-bit data pointers and 32-bit
  1534.     function pointers, or vice versa.
  1535.  
  1536.     Some 64-bit Cray machines represent int * in the lower 48 bits
  1537.     of a word; char * additionally uses the upper 16 bits to
  1538.     indicate a byte address within a word.
  1539.  
  1540.     References: K&R1 Sec. A14.4 p. 211.
  1541.  
  1542. 5.20:    What does a run-time "null pointer assignment" error mean?
  1543.     How can I track it down?
  1544.  
  1545. A:    This message, which typically occurs with MS-DOS compilers, means
  1546.     that you've written, via a null (perhaps because uninitialized)
  1547.     pointer, to an invalid location (probably offset 0 in the
  1548.     default data segment).
  1549.  
  1550.     A debugger may let you set a data watchpoint on location 0.
  1551.     Alternatively, you could write a bit of code to stash away a
  1552.     copy of 20 or so bytes from location 0, and periodically check
  1553.     that the memory at location 0 hasn't changed.  See also question
  1554.     16.8.
  1555.  
  1556.  
  1557. Section 6. Arrays and Pointers
  1558.  
  1559. 6.1:    I had the definition char a[6] in one source file, and in
  1560.     another I declared extern char *a.  Why didn't it work?
  1561.  
  1562. A:    In one source file you defind an array of characters and in the
  1563.     other you declared a pointer to characters.  The declaration
  1564.     extern char *a simply does not match the actual definition.
  1565.     The type pointer-to-type-T is not the same as array-of-type-T.
  1566.     Use extern char a[].
  1567.  
  1568.     References: ISO Sec. 6.5.4.2; CT&P Sec. 3.3 pp. 33-4, Sec. 4.5
  1569.     pp. 64-5.
  1570.  
  1571. 6.2:    But I heard that char a[] was identical to char *a.
  1572.  
  1573. A:    Not at all.  (What you heard has to do with formal parameters to
  1574.     functions; see question 6.4.)  Arrays are not pointers.  The
  1575.     array declaration char a[6] requests that space for six
  1576.     characters be set aside, to be known by the name "a".  That is,
  1577.     there is a location named "a" at which six characters can sit.
  1578.     The pointer declaration char *p, on the other hand, requests a
  1579.     place which holds a pointer, to be known by the name "p".  This
  1580.     pointer can point almost anywhere: to any char, or to any
  1581.     contiguous array of chars, or nowhere (see also questions 5.1
  1582.     and 1.30).
  1583.  
  1584.     As usual, a picture is worth a thousand words.  The declarations
  1585.  
  1586.         char a[] = "hello";
  1587.         char *p = "world";
  1588.  
  1589.     would initialize data structures which could be represented like
  1590.     this:
  1591.            +---+---+---+---+---+---+
  1592.         a: | h | e | l | l | o |\0 |
  1593.            +---+---+---+---+---+---+
  1594.            +-----+     +---+---+---+---+---+---+
  1595.         p: |  *======> | w | o | r | l | d |\0 |
  1596.            +-----+     +---+---+---+---+---+---+
  1597.  
  1598.     It is important to realize that a reference like x[3] generates
  1599.     different code depending on whether x is an array or a pointer.
  1600.     Given the declarations above, when the compiler sees the
  1601.     expression a[3], it emits code to start at the location "a",
  1602.     move three past it, and fetch the character there.  When it sees
  1603.     the expression p[3], it emits code to start at the location "p",
  1604.     fetch the pointer value there, add three to the pointer, and
  1605.     finally fetch the character pointed to.  In other words, a[3] is
  1606.     three places past (the start of) the object *named* a, while
  1607.     p[3] is three places past the object *pointed to* by p.  In the
  1608.     example above, both a[3] and p[3] happen to be the character
  1609.     'l', but the compiler gets there differently.  (The essential
  1610.     difference is that the values of an array like a and a pointer
  1611.     like p are computed differently *whenever* they appear in
  1612.     expressions, whether or not they are being subscripted, as
  1613.     explained further in the next question.)
  1614.  
  1615.     References: K&R2 Sec. 5.5 p. 104; CT&P Sec. 4.5 pp. 64-5.
  1616.  
  1617. 6.3:    So what is meant by the "equivalence of pointers and arrays" in
  1618.     C?
  1619.  
  1620. A:    Much of the confusion surrounding arrays and pointers in C can
  1621.     be traced to a misunderstanding of this statement.  Saying that
  1622.     arrays and pointers are "equivalent" means neither that they are
  1623.     identical nor even interchangeable.  What it means is that array
  1624.     and pointer arithmetic is defined such that a pointer can be
  1625.     conveniently used to access an array or to simulate an array.
  1626.  
  1627.     Specifically, the cornerstone of the equivalence is this key
  1628.     definition:
  1629.  
  1630.         An lvalue of type array-of-T which appears in an
  1631.         expression decays (with three exceptions) into a
  1632.         pointer to its first element; the type of the
  1633.         resultant pointer is pointer-to-T.
  1634.  
  1635.     That is, whenever an array appears in an expression,
  1636.     the compiler implicitly generates a pointer to the array's
  1637.     first element, just as if the programmer had written &a[0].
  1638.     (The exceptions are when the array is the operand of a sizeof or
  1639.     & operator, or is a string literal initializer for a character
  1640.     array.)
  1641.  
  1642.     As a consequence of this definition, the compiler doesn't apply
  1643.     the array subscripting operator [] that differently to arrays
  1644.     and pointers, after all.  In an expression of the form a[i], the
  1645.     array decays into a pointer, following the rule above, and is
  1646.     then subscripted just as would be a pointer variable in the
  1647.     expression p[i] (although the eventual memory accesses will be
  1648.     different, as explained in question 6.2).  If you were to assign
  1649.     the array's address to the pointer:
  1650.  
  1651.         p = a;
  1652.  
  1653.     then p[3] and a[3] would access the same element.
  1654.  
  1655.     See also questions 6.8 and 6.14.
  1656.  
  1657.     References: K&R1 Sec. 5.3 pp. 93-6; K&R2 Sec. 5.3 p. 99; ISO
  1658.     Sec. 6.2.2.1, Sec. 6.3.2.1, Sec. 6.3.6; H&S Sec. 5.4.1 p. 124.
  1659.  
  1660. 6.4:    Then why are array and pointer declarations interchangeable as
  1661.     function formal parameters?
  1662.  
  1663. A:    It's supposed to be a convenience.
  1664.  
  1665.     Since arrays decay immediately into pointers, an array is never
  1666.     actually passed to a function.  Allowing pointer parameters to
  1667.     be declared as arrays is a simply a way of making it look as
  1668.     though an array was being passed, perhaps because the parameter
  1669.     will be used within the function as if it were an array.
  1670.     Specifically, any parameter declarations which "look like"
  1671.     arrays, e.g.
  1672.  
  1673.         void f(char a[])
  1674.         { ... }
  1675.  
  1676.     are treated by the compiler as if they were pointers, since that
  1677.     is what the function will receive if an array is passed:
  1678.  
  1679.         void f(char *a)
  1680.         { ... }
  1681.  
  1682.     This conversion holds only within function formal parameter
  1683.     declarations, nowhere else.  If the conversion bothers you,
  1684.     avoid it; many programmers have concluded that the confusion it
  1685.     causes outweighs the small advantage of having the declaration
  1686.     "look like" the call or the uses within the function.
  1687.  
  1688.     See also question 6.21.
  1689.  
  1690.     References: K&R1 Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R2
  1691.     Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; ISO
  1692.     Sec. 6.5.4.3, Sec. 6.7.1, Sec. 6.9.6; H&S Sec. 9.3 p. 271; CT&P
  1693.     Sec. 3.3 pp. 33-4.
  1694.  
  1695. 6.7:    How can an array be an lvalue, if you can't assign to it?
  1696.  
  1697. A:    The ANSI C Standard defines a "modifiable lvalue," which an
  1698.     array is not.
  1699.  
  1700.     References: ISO Sec. 6.2.2.1; Rationale Sec. 3.2.2.1; H&S
  1701.     Sec. 7.1 p. 179.
  1702.  
  1703. 6.8:    Practically speaking, what is the difference between arrays and
  1704.     pointers?
  1705.  
  1706. A:    Arrays automatically allocate space, but can't be relocated or
  1707.     resized.  Pointers must be explicitly assigned to point to
  1708.     allocated space (perhaps using malloc), but can be reassigned
  1709.     (i.e. pointed at different objects) at will, and have many other
  1710.     uses besides serving as the base of blocks of memory.
  1711.  
  1712.     Due to the so-called equivalence of arrays and pointers (see
  1713.     question 6.3), arrays and pointers often seem interchangeable,
  1714.     and in particular a pointer to a block of memory assigned by
  1715.     malloc is frequently treated (and can be referenced using [])
  1716.     exactly as if it were a true array.  See questions 6.14 and
  1717.     6.16.  (Be careful with sizeof, though.)
  1718.  
  1719.     See also questions 1.32 and 20.14.
  1720.  
  1721. 6.9:    Someone explained to me that arrays were really just constant
  1722.     pointers.
  1723.  
  1724. A:    This is a bit of an oversimplification.  An array name is
  1725.     "constant" in that it cannot be assigned to, but an array is
  1726.     *not* a pointer, as the discussion and pictures in question 6.2
  1727.     should make clear.  See also questions 6.3 and 6.8.
  1728.  
  1729. 6.11:    I came across some "joke" code containing the "expression"
  1730.     5["abcdef"] .  How can this be legal C?
  1731.  
  1732. A:    Yes, Virginia, array subscripting is commutative in C.  This
  1733.     curious fact follows from the pointer definition of array
  1734.     subscripting, namely that a[e] is identical to *((a)+(e)), for
  1735.     *any* two expressions a and e, as long as one of them is a
  1736.     pointer expression and one is integral.  This unsuspected
  1737.     commutativity is often mentioned in C texts as if it were
  1738.     something to be proud of, but it finds no useful application
  1739.     outside of the Obfuscated C Contest (see question 20.36).
  1740.  
  1741.     References: Rationale Sec. 3.3.2.1; H&S Sec. 5.4.1 p. 124,
  1742.     Sec. 7.4.1 pp. 186-7.
  1743.  
  1744. 6.12:    Since array references decay into pointers, if arr is an array,
  1745.     what's the difference between arr and &arr?
  1746.  
  1747. A:    The type.
  1748.  
  1749.     In Standard C, &arr yields a pointer, of type pointer-to-array-
  1750.     of-T, to the entire array.  (In pre-ANSI C, the & in &arr
  1751.     generally elicited a warning, and was generally ignored.)  Under
  1752.     all C compilers, a simple reference (without an explicit &) to
  1753.     an array yields a pointer, of type pointer-to-T, to the array's
  1754.     first element.  (See also questions 6.3, 6.13, and 6.18.)
  1755.  
  1756.     References: ISO Sec. 6.2.2.1, Sec. 6.3.3.2; Rationale
  1757.     Sec. 3.3.3.2; H&S Sec. 7.5.6 p. 198.
  1758.  
  1759. 6.13:    How do I declare a pointer to an array?
  1760.  
  1761. A:    Usually, you don't want to.  When people speak casually of a
  1762.     pointer to an array, they usually mean a pointer to its first
  1763.     element.
  1764.  
  1765.     Instead of a pointer to an array, consider using a pointer to
  1766.     one of the array's elements.  Arrays of type T decay into
  1767.     pointers to type T (see question 6.3), which is convenient;
  1768.     subscripting or incrementing the resultant pointer will access
  1769.     the individual members of the array.  True pointers to arrays,
  1770.     when subscripted or incremented, step over entire arrays, and
  1771.     are generally useful only when operating on arrays of arrays, if
  1772.     at all.  (See question 6.18.)
  1773.  
  1774.     If you really need to declare a pointer to an entire array, use
  1775.     something like "int (*ap)[N];" where N is the size of the array.
  1776.     (See also question 1.21.)  If the size of the array is unknown,
  1777.     N can in principle be omitted, but the resulting type, "pointer
  1778.     to array of unknown size," is useless.
  1779.  
  1780.     See also question 6.12 above.
  1781.  
  1782.     References: ISO Sec. 6.2.2.1.
  1783.  
  1784. 6.14:    How can I set an array's size at run time?
  1785.     How can I avoid fixed-sized arrays?
  1786.  
  1787. A:    The equivalence between arrays and pointers (see question 6.3)
  1788.     allows a pointer to malloc'ed memory to simulate an array
  1789.     quite effectively.  After executing
  1790.  
  1791.         #include <stdlib.h>
  1792.         int *dynarray;
  1793.         dynarray = malloc(10 * sizeof(int));
  1794.  
  1795.     (and if the call to malloc succeeds), you can reference
  1796.     dynarray[i] (for i from 0 to 9) almost as if dynarray were a
  1797.     conventional, statically-allocated array (int a[10]).  The only
  1798.     difference is that sizeof will not give the size of the "array".
  1799.     See also questions 1.31b, 6.16, and 7.7.
  1800.  
  1801. 6.15:    How can I declare local arrays of a size matching a passed-in
  1802.     array?
  1803.  
  1804. A:    Until recently, you couldn't.  Array dimensions in C
  1805.     traditionally had to be compile-time constants.  C9X will
  1806.     introduce variable-length arrays (VLA's) which will solve this
  1807.     problem; local arrays may have sizes set by variables or other
  1808.     expressions, perhaps involving function parameters.  (gcc has
  1809.     provided parameterized arrays as an extension for some time.)
  1810.     If you can't use C9X or gcc, you'll have to use malloc(), and
  1811.     remember to call free() before the function returns.  See also
  1812.     questions 6.14, 6.16, 6.19, 7.22, and maybe 7.32.
  1813.  
  1814.     References: ISO Sec. 6.4, Sec. 6.5.4.2; C9X Sec. 6.5.5.2.
  1815.  
  1816. 6.16:    How can I dynamically allocate a multidimensional array?
  1817.  
  1818. A:    The traditional solution is to allocate an array of pointers,
  1819.     and then initialize each pointer to a dynamically-allocated
  1820.     "row."  Here is a two-dimensional example:
  1821.  
  1822.         #include <stdlib.h>
  1823.  
  1824.         int **array1 = malloc(nrows * sizeof(int *));
  1825.         for(i = 0; i < nrows; i++)
  1826.             array1[i] = malloc(ncolumns * sizeof(int));
  1827.  
  1828.     (In real code, of course, all of malloc's return values would
  1829.     be checked.)
  1830.  
  1831.     You can keep the array's contents contiguous, at the cost of
  1832.     making later reallocation of individual rows more difficult,
  1833.     with a bit of explicit pointer arithmetic:
  1834.  
  1835.         int **array2 = malloc(nrows * sizeof(int *));
  1836.         array2[0] = malloc(nrows * ncolumns * sizeof(int));
  1837.         for(i = 1; i < nrows; i++)
  1838.             array2[i] = array2[0] + i * ncolumns;
  1839.  
  1840.     In either case, the elements of the dynamic array can be
  1841.     accessed with normal-looking array subscripts: arrayx[i][j]
  1842.     (for 0 <= i < nrows and 0 <= j < ncolumns).
  1843.  
  1844.     If the double indirection implied by the above schemes is for
  1845.     some reason unacceptable, you can simulate a two-dimensional
  1846.     array with a single, dynamically-allocated one-dimensional
  1847.     array:
  1848.  
  1849.         int *array3 = malloc(nrows * ncolumns * sizeof(int));
  1850.  
  1851.     However, you must now perform subscript calculations manually,
  1852.     accessing the i,jth element with array3[i * ncolumns + j].  (A
  1853.     macro could hide the explicit calculation, but invoking it would
  1854.     require parentheses and commas which wouldn't look exactly like
  1855.     multidimensional array syntax, and the macro would need access
  1856.     to at least one of the dimensions, as well.  See also question
  1857.     6.19.)
  1858.  
  1859.     Yet another option is to use pointers to arrays:
  1860.  
  1861.         int (*array4)[NCOLUMNS] = malloc(nrows * sizeof(*array4));
  1862.  
  1863.     but the syntax starts getting horrific and at most one dimension
  1864.     may be specified at run time.
  1865.  
  1866.     With all of these techniques, you may of course need to remember
  1867.     to free the arrays (which may take several steps; see question
  1868.     7.23) when they are no longer needed, and you cannot necessarily
  1869.     intermix dynamically-allocated arrays with conventional,
  1870.     statically-allocated ones (see question 6.20, and also question
  1871.     6.18).
  1872.  
  1873.     Finally, in C9X you can use a variable-length array.
  1874.  
  1875.     All of these techniques can also be extended to three or more
  1876.     dimensions.
  1877.  
  1878.     References: C9X Sec. 6.5.5.2.
  1879.  
  1880. 6.17:    Here's a neat trick: if I write
  1881.  
  1882.         int realarray[10];
  1883.         int *array = &realarray[-1];
  1884.  
  1885.     I can treat "array" as if it were a 1-based array.
  1886.  
  1887. A:    Although this technique is attractive (and was used in old
  1888.     editions of the book _Numerical Recipes in C_), it is not
  1889.     strictly conforming to the C Standard.  Pointer arithmetic
  1890.     is defined only as long as the pointer points within the same
  1891.     allocated block of memory, or to the imaginary "terminating"
  1892.     element one past it; otherwise, the behavior is undefined,
  1893.     *even if the pointer is not dereferenced*.  The code above
  1894.     could fail if, while subtracting the offset, an illegal
  1895.     address were generated (perhaps because the address tried
  1896.     to "wrap around" past the beginning of some memory segment).
  1897.  
  1898.     References: K&R2 Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7
  1899.     pp. 205-6; ISO Sec. 6.3.6; Rationale Sec. 3.2.2.3.
  1900.  
  1901. 6.18:    My compiler complained when I passed a two-dimensional array to
  1902.     a function expecting a pointer to a pointer.
  1903.  
  1904. A:    The rule (see question 6.3) by which arrays decay into pointers
  1905.     is not applied recursively.  An array of arrays (i.e. a two-
  1906.     dimensional array in C) decays into a pointer to an array, not a
  1907.     pointer to a pointer.  Pointers to arrays can be confusing, and
  1908.     must be treated carefully; see also question 6.13.
  1909.  
  1910.     If you are passing a two-dimensional array to a function:
  1911.  
  1912.         int array[NROWS][NCOLUMNS];
  1913.         f(array);
  1914.  
  1915.     the function's declaration must match:
  1916.  
  1917.         void f(int a[][NCOLUMNS])
  1918.         { ... }
  1919.  
  1920.     or
  1921.  
  1922.         void f(int (*ap)[NCOLUMNS])    /* ap is a pointer to an array */
  1923.         { ... }
  1924.  
  1925.     In the first declaration, the compiler performs the usual
  1926.     implicit parameter rewriting of "array of array" to "pointer to
  1927.     array" (see questions 6.3 and 6.4); in the second form the
  1928.     pointer declaration is explicit.  Since the called function does
  1929.     not allocate space for the array, it does not need to know the
  1930.     overall size, so the number of rows, NROWS, can be omitted.  The
  1931.     width of the array is still important, so the column dimension
  1932.     NCOLUMNS (and, for three- or more dimensional arrays, the
  1933.     intervening ones) must be retained.
  1934.  
  1935.     If a function is already declared as accepting a pointer to a
  1936.     pointer, it is almost certainly meaningless to pass a two-
  1937.     dimensional array directly to it.
  1938.  
  1939.     See also questions 6.12 and 6.15.
  1940.  
  1941.     References: K&R1 Sec. 5.10 p. 110; K&R2 Sec. 5.9 p. 113; H&S
  1942.     Sec. 5.4.3 p. 126.
  1943.  
  1944. 6.19:    How do I write functions which accept two-dimensional arrays
  1945.     when the width is not known at compile time?
  1946.  
  1947. A:    It's not always easy.  One way is to pass in a pointer to the
  1948.     [0][0] element, along with the two dimensions, and simulate
  1949.     array subscripting "by hand":
  1950.  
  1951.         void f2(int *aryp, int nrows, int ncolumns)
  1952.         { ... array[i][j] is accessed as aryp[i * ncolumns + j] ... }
  1953.  
  1954.     This function could be called with the array from question 6.18
  1955.     as
  1956.  
  1957.         f2(&array[0][0], NROWS, NCOLUMNS);
  1958.  
  1959.     It must be noted, however, that a program which performs
  1960.     multidimensional array subscripting "by hand" in this way is not
  1961.     in strict conformance with the ANSI C Standard; according to an
  1962.     official interpretation, the behavior of accessing
  1963.     (&array[0][0])[x] is not defined for x >= NCOLUMNS.
  1964.  
  1965.     C9X will allow variable-length arrays, and once compilers which
  1966.     accept C9X's extensions become widespread, this will probably
  1967.     become the preferred solution.  (gcc has supported variable-
  1968.     sized arrays for some time.)
  1969.  
  1970.     When you want to be able to use a function on multidimensional
  1971.     arrays of various sizes, one solution is to simulate all the
  1972.     arrays dynamically, as in question 6.16.
  1973.  
  1974.     See also questions 6.18, 6.20, and 6.15.
  1975.  
  1976.     References: ISO Sec. 6.3.6; C9X Sec. 6.5.5.2.
  1977.  
  1978. 6.20:    How can I use statically- and dynamically-allocated
  1979.     multidimensional arrays interchangeably when passing them to
  1980.     functions?
  1981.  
  1982. A:    There is no single perfect method.  Given the declarations
  1983.  
  1984.         int array[NROWS][NCOLUMNS];
  1985.         int **array1;            /* ragged */
  1986.         int **array2;            /* contiguous */
  1987.         int *array3;            /* "flattened" */
  1988.         int (*array4)[NCOLUMNS];
  1989.  
  1990.     with the pointers initialized as in the code fragments in
  1991.     question 6.16, and functions declared as
  1992.  
  1993.         void f1a(int a[][NCOLUMNS], int nrows, int ncolumns);
  1994.         void f1b(int (*a)[NCOLUMNS], int nrows, int ncolumns);
  1995.         void f2(int *aryp, int nrows, int ncolumns);
  1996.         void f3(int **pp, int nrows, int ncolumns);
  1997.  
  1998.     where f1a() and f1b() accept conventional two-dimensional
  1999.     arrays, f2() accepts a "flattened" two-dimensional array, and
  2000.     f3() accepts a pointer-to-pointer, simulated array (see also
  2001.     questions 6.18 and 6.19), the following calls should work as
  2002.     expected:
  2003.  
  2004.         f1a(array, NROWS, NCOLUMNS);
  2005.         f1b(array, NROWS, NCOLUMNS);
  2006.         f1a(array4, nrows, NCOLUMNS);
  2007.         f1b(array4, nrows, NCOLUMNS);
  2008.         f2(&array[0][0], NROWS, NCOLUMNS);
  2009.         f2(*array, NROWS, NCOLUMNS);
  2010.         f2(*array2, nrows, ncolumns);
  2011.         f2(array3, nrows, ncolumns);
  2012.         f2(*array4, nrows, NCOLUMNS);
  2013.         f3(array1, nrows, ncolumns);
  2014.         f3(array2, nrows, ncolumns);
  2015.  
  2016.     The following calls would probably work on most systems, but
  2017.     involve questionable casts, and work only if the dynamic
  2018.     ncolumns matches the static NCOLUMNS:
  2019.  
  2020.         f1a((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
  2021.         f1a((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
  2022.         f1b((int (*)[NCOLUMNS])array3, nrows, ncolumns);
  2023.         f1b((int (*)[NCOLUMNS])array3, nrows, ncolumns);
  2024.  
  2025.     It must again be noted that passing &array[0][0] (or,
  2026.     equivalently, *array) to f2() is not strictly conforming; see
  2027.     question 6.19.
  2028.  
  2029.     If you can understand why all of the above calls work and are
  2030.     written as they are, and if you understand why the combinations
  2031.     that are not listed would not work, then you have a *very* good
  2032.     understanding of arrays and pointers in C.
  2033.  
  2034.     Rather than worrying about all of this, one approach to using
  2035.     multidimensional arrays of various sizes is to make them *all*
  2036.     dynamic, as in question 6.16.  If there are no static
  2037.     multidimensional arrays -- if all arrays are allocated like
  2038.     array1 or array2 in question 6.16 -- then all functions can be
  2039.     written like f3().
  2040.  
  2041. 6.21:    Why doesn't sizeof properly report the size of an array when the
  2042.     array is a parameter to a function?
  2043.  
  2044. A:    The compiler pretends that the array parameter was declared as a
  2045.     pointer (see question 6.4), and sizeof reports the size of the
  2046.     pointer.
  2047.  
  2048.     References: H&S Sec. 7.5.2 p. 195.
  2049.  
  2050.  
  2051. Section 7. Memory Allocation
  2052.  
  2053. 7.1:    Why doesn't this fragment work?
  2054.  
  2055.         char *answer;
  2056.         printf("Type something:\n");
  2057.         gets(answer);
  2058.         printf("You typed \"%s\"\n", answer);
  2059.  
  2060. A:    The pointer variable answer, which is handed to gets() as the
  2061.     location into which the response should be stored, has not been
  2062.     set to point to any valid storage.  That is, we cannot say where
  2063.     the pointer answer points.  (Since local variables are not
  2064.     initialized, and typically contain garbage, it is not even
  2065.     guaranteed that answer starts out as a null pointer.
  2066.     See questions 1.30 and 5.1.)
  2067.  
  2068.     The simplest way to correct the question-asking program is to
  2069.     use a local array, instead of a pointer, and let the compiler
  2070.     worry about allocation:
  2071.  
  2072.         #include <stdio.h>
  2073.         #include <string.h>
  2074.  
  2075.         char answer[100], *p;
  2076.         printf("Type something:\n");
  2077.         fgets(answer, sizeof answer, stdin);
  2078.         if((p = strchr(answer, '\n')) != NULL)
  2079.             *p = '\0';
  2080.         printf("You typed \"%s\"\n", answer);
  2081.  
  2082.     This example also uses fgets() instead of gets(), so that the
  2083.     end of the array cannot be overwritten.  (See question 12.23.
  2084.     Unfortunately for this example, fgets() does not automatically
  2085.     delete the trailing \n, as gets() would.)  It would also be
  2086.     possible to use malloc() to allocate the answer buffer.
  2087.  
  2088. 7.2:    I can't get strcat() to work.  I tried
  2089.  
  2090.         char *s1 = "Hello, ";
  2091.         char *s2 = "world!";
  2092.         char *s3 = strcat(s1, s2);
  2093.  
  2094.     but I got strange results.
  2095.  
  2096. A:    As in question 7.1 above, the main problem here is that space
  2097.     for the concatenated result is not properly allocated.  C does
  2098.     not provide an automatically-managed string type.  C compilers
  2099.     only allocate memory for objects explicitly mentioned in the
  2100.     source code (in the case of strings, this includes character
  2101.     arrays and string literals).  The programmer must arrange for
  2102.     sufficient space for the results of run-time operations such as
  2103.     string concatenation, typically by declaring arrays, or by
  2104.     calling malloc().
  2105.  
  2106.     strcat() performs no allocation; the second string is appended
  2107.     to the first one, in place.  Therefore, one fix would be to
  2108.     declare the first string as an array:
  2109.  
  2110.         char s1[20] = "Hello, ";
  2111.  
  2112.     Since strcat() returns the value of its first argument (s1, in
  2113.     this case), the variable s3 is superfluous; after the call to
  2114.     strcat(), s1 contains the result.
  2115.  
  2116.     The original call to strcat() in the question actually has two
  2117.     problems: the string literal pointed to by s1, besides not being
  2118.     big enough for any concatenated text, is not necessarily
  2119.     writable at all.  See question 1.32.
  2120.  
  2121.     References: CT&P Sec. 3.2 p. 32.
  2122.  
  2123. 7.3:    But the man page for strcat() says that it takes two char *'s as
  2124.     arguments.  How am I supposed to know to allocate things?
  2125.  
  2126. A:    In general, when using pointers you *always* have to consider
  2127.     memory allocation, if only to make sure that the compiler is
  2128.     doing it for you.  If a library function's documentation does
  2129.     not explicitly mention allocation, it is usually the caller's
  2130.     problem.
  2131.  
  2132.     The Synopsis section at the top of a Unix-style man page or in
  2133.     the ANSI C standard can be misleading.  The code fragments
  2134.     presented there are closer to the function definitions used by
  2135.     an implementor than the invocations used by the caller.  In
  2136.     particular, many functions which accept pointers (e.g. to
  2137.     structures or strings) are usually called with a pointer to some
  2138.     object (a structure, or an array -- see questions 6.3 and 6.4)
  2139.     which the caller has allocated.  Other common examples are
  2140.     time() (see question 13.12) and stat().
  2141.  
  2142. 7.3b:    I just tried the code
  2143.  
  2144.         char *p;
  2145.         strcpy(p, "abc");
  2146.  
  2147.     and it worked.  How?  Why didn't it crash?
  2148.  
  2149. A:    You got lucky, I guess.  The memory pointed to by the
  2150.     unitialized pointer p happened to be writable by you,
  2151.     and apparently was not already in use for anything vital.
  2152.  
  2153. 7.3c:    How much memory does a pointer variable allocate?
  2154.  
  2155. A:    That's a pretty misleading question.  When you declare
  2156.     a pointer variable, as in
  2157.  
  2158.         char *p;
  2159.  
  2160.     you (or, more properly, the compiler) have allocated only enough
  2161.     memory to hold the pointer itself; that is, in this case you
  2162.     have allocated sizeof(char *) bytes of memory.  But you have
  2163.     not yet allocated *any* memory for the pointer to point to.
  2164.     See also questions 7.1 and 7.2.
  2165.  
  2166. 7.5a:    I have a function that is supposed to return a string, but when
  2167.     it returns to its caller, the returned string is garbage.
  2168.  
  2169. A:    Make sure that the pointed-to memory is properly allocated.
  2170.     For example, make sure you have *not* done something like
  2171.  
  2172.         char *itoa(int n)
  2173.         {
  2174.             char retbuf[20];        /* WRONG */
  2175.             sprintf(retbuf, "%d", n);
  2176.             return retbuf;            /* WRONG */
  2177.         }
  2178.  
  2179.     One fix (which is imperfect, especially if the function in
  2180.     question is called recursively, or if several of its return
  2181.     values are needed simultaneously) would be to declare the return
  2182.     buffer as
  2183.  
  2184.             static char retbuf[20];
  2185.  
  2186.     See also questions 7.5b, 12.21, and 20.1.
  2187.  
  2188.     References: ISO Sec. 6.1.2.4.
  2189.  
  2190. 7.5b:    So what's the right way to return a string or other aggregate?
  2191.  
  2192. A:    The returned pointer should be to a statically-allocated buffer,
  2193.     or to a buffer passed in by the caller, or to memory obtained
  2194.     with malloc(), but *not* to a local (automatic) array.
  2195.  
  2196.     See also question 20.1.
  2197.  
  2198. 7.6:    Why am I getting "warning: assignment of pointer from integer
  2199.     lacks a cast" for calls to malloc()?
  2200.  
  2201. A:    Have you #included <stdlib.h>, or otherwise arranged for
  2202.     malloc() to be declared properly?  See also question 1.25.
  2203.  
  2204.     References: H&S Sec. 4.7 p. 101.
  2205.  
  2206. 7.7:    Why does some code carefully cast the values returned by malloc
  2207.     to the pointer type being allocated?
  2208.  
  2209. A:    Before ANSI/ISO Standard C introduced the void * generic pointer
  2210.     type, these casts were typically required to silence warnings
  2211.     (and perhaps induce conversions) when assigning between
  2212.     incompatible pointer types.
  2213.  
  2214.     Under ANSI/ISO Standard C, these casts are no longer necessary,
  2215.     and in fact modern practice discourages them, since they can
  2216.     camouflage important warnings which would otherwise be generated
  2217.     if malloc() happened not to be declared correctly; see question
  2218.     7.6 above.  (However, the casts are typically seen in C code
  2219.     which for one reason or another is intended to be compatible
  2220.     with C++, where explicit casts from void * are required.)
  2221.  
  2222.     References: H&S Sec. 16.1 pp. 386-7.
  2223.  
  2224. 7.8:    I see code like
  2225.  
  2226.         char *p = malloc(strlen(s) + 1);
  2227.         strcpy(p, s);
  2228.  
  2229.     Shouldn't that be malloc((strlen(s) + 1) * sizeof(char))?
  2230.  
  2231. A:    It's never necessary to multiply by sizeof(char), since
  2232.     sizeof(char) is, by definition, exactly 1.  (On the other
  2233.     hand, multiplying by sizeof(char) doesn't hurt, and in some
  2234.     circumstances may help by introducing a size_t into the
  2235.     expression.)  See also question 8.9.
  2236.  
  2237.     References: ISO Sec. 6.3.3.4; H&S Sec. 7.5.2 p. 195.
  2238.  
  2239. 7.14:    I've heard that some operating systems don't actually allocate
  2240.     malloc'ed memory until the program tries to use it.  Is this
  2241.     legal?
  2242.  
  2243. A:    It's hard to say.  The Standard doesn't say that systems can act
  2244.     this way, but it doesn't explicitly say that they can't, either.
  2245.  
  2246.     References: ISO Sec. 7.10.3.
  2247.  
  2248. 7.16:    I'm allocating a large array for some numeric work, using the
  2249.     line
  2250.  
  2251.         double *array = malloc(300 * 300 * sizeof(double));
  2252.  
  2253.     malloc() isn't returning null, but the program is acting
  2254.     strangely, as if it's overwriting memory, or malloc() isn't
  2255.     allocating as much as I asked for, or something.
  2256.  
  2257. A:    Notice that 300 x 300 is 90,000, which will not fit in a 16-bit
  2258.     int, even before you multiply it by sizeof(double).  If you
  2259.     need to allocate this much memory, you'll have to be careful.
  2260.     If size_t (the type accepted by malloc()) is a 32-bit type on
  2261.     your machine, but int is 16 bits, you might be able to get away
  2262.     with writing 300 * (300 * sizeof(double)) (see question 3.14).
  2263.     Otherwise, you'll have to break your data structure up into
  2264.     smaller chunks, or use a 32-bit machine or compiler, or use
  2265.     some nonstandard memory allocation functions.  See also
  2266.     question 19.23.
  2267.  
  2268. 7.17:    I've got 8 meg of memory in my PC.  Why can I only seem to
  2269.     malloc 640K or so?
  2270.  
  2271. A:    Under the segmented architecture of PC compatibles, it can be
  2272.     difficult to use more than 640K with any degree of transparency,
  2273.     especially under MS-DOS.  See also question 19.23.
  2274.  
  2275. 7.19:    My program is crashing, apparently somewhere down inside malloc,
  2276.     but I can't see anything wrong with it.  Is there a bug in
  2277.     malloc()?
  2278.  
  2279. A:    It is unfortunately very easy to corrupt malloc's internal data
  2280.     structures, and the resulting problems can be stubborn.  The
  2281.     most common source of problems is writing more to a malloc'ed
  2282.     region than it was allocated to hold; a particularly common bug
  2283.     is to malloc(strlen(s)) instead of strlen(s) + 1.  Other
  2284.     problems may involve using pointers to memory that has been
  2285.     freed, freeing pointers twice, freeing pointers not obtained
  2286.     from malloc, or trying to realloc a null pointer (see question
  2287.     7.30).
  2288.  
  2289.     See also questions 7.26, 16.8, and 18.2.
  2290.  
  2291. 7.20:    You can't use dynamically-allocated memory after you free it,
  2292.     can you?
  2293.  
  2294. A:    No.  Some early documentation for malloc() stated that the
  2295.     contents of freed memory were "left undisturbed," but this ill-
  2296.     advised guarantee was never universal and is not required by the
  2297.     C Standard.
  2298.  
  2299.     Few programmers would use the contents of freed memory
  2300.     deliberately, but it is easy to do so accidentally.  Consider
  2301.     the following (correct) code for freeing a singly-linked list:
  2302.  
  2303.         struct list *listp, *nextp;
  2304.         for(listp = base; listp != NULL; listp = nextp) {
  2305.             nextp = listp->next;
  2306.             free(listp);
  2307.         }
  2308.  
  2309.     and notice what would happen if the more-obvious loop iteration
  2310.     expression listp = listp->next were used, without the temporary
  2311.     nextp pointer.
  2312.  
  2313.     References: K&R2 Sec. 7.8.5 p. 167; ISO Sec. 7.10.3; Rationale
  2314.     Sec. 4.10.3.2; H&S Sec. 16.2 p. 387; CT&P Sec. 7.10 p. 95.
  2315.  
  2316. 7.21:    Why isn't a pointer null after calling free()?
  2317.     How unsafe is it to use (assign, compare) a pointer value after
  2318.     it's been freed?
  2319.  
  2320. A:    When you call free(), the memory pointed to by the passed
  2321.     pointer is freed, but the value of the pointer in the caller
  2322.     probably remains unchanged, because C's pass-by-value semantics
  2323.     mean that called functions never permanently change the values
  2324.     of their arguments.  (See also question 4.8.)
  2325.  
  2326.     A pointer value which has been freed is, strictly speaking,
  2327.     invalid, and *any* use of it, even if is not dereferenced, can
  2328.     theoretically lead to trouble, though as a quality of
  2329.     implementation issue, most implementations will probably not go
  2330.     out of their way to generate exceptions for innocuous uses of
  2331.     invalid pointers.
  2332.  
  2333.     References: ISO Sec. 7.10.3; Rationale Sec. 3.2.2.3.
  2334.  
  2335. 7.22:    When I call malloc() to allocate memory for a pointer which is
  2336.     local to a function, do I have to explicitly free() it?
  2337.  
  2338. A:    Yes.  Remember that a pointer is different from what it points
  2339.     to.  Local variables are deallocated when the function returns,
  2340.     but in the case of a pointer variable, this means that the
  2341.     pointer is deallocated, *not* what it points to.  Memory
  2342.     allocated with malloc() always persists until you explicitly
  2343.     free it.  In general, for every call to malloc(), there should
  2344.     be a corresponding call to free().
  2345.  
  2346. 7.23:    I'm allocating structures which contain pointers to other
  2347.     dynamically-allocated objects.  When I free a structure, do I
  2348.     also have to free each subsidiary pointer?
  2349.  
  2350. A:    Yes.  In general, you must arrange that each pointer returned
  2351.     from malloc() be individually passed to free(), exactly once (if
  2352.     it is freed at all).  A good rule of thumb is that for each call
  2353.     to malloc() in a program, you should be able to point at the
  2354.     call to free() which frees the memory allocated by that malloc()
  2355.     call.
  2356.  
  2357.     See also question 7.24.
  2358.  
  2359. 7.24:    Must I free allocated memory before the program exits?
  2360.  
  2361. A:    You shouldn't have to.  A real operating system definitively
  2362.     reclaims all memory and other resources when a program exits.
  2363.     Nevertheless, some personal computers are said not to reliably
  2364.     recover memory, and all that can be inferred from the ANSI/ISO C
  2365.     Standard is that this is a "quality of implementation issue."
  2366.  
  2367.     References: ISO Sec. 7.10.3.2.
  2368.  
  2369. 7.25:    I have a program which mallocs and later frees a lot of memory,
  2370.     but I can see from the operating system that memory usage
  2371.     doesn't actually go back down.
  2372.  
  2373. A:    Most implementations of malloc/free do not return freed memory
  2374.     to the operating system, but merely make it available for future
  2375.     malloc() calls within the same program.
  2376.  
  2377. 7.26:    How does free() know how many bytes to free?
  2378.  
  2379. A:    The malloc/free implementation remembers the size of each block
  2380.     as it is allocated, so it is not necessary to remind it of the
  2381.     size when freeing.
  2382.  
  2383. 7.27:    So can I query the malloc package to find out how big an
  2384.     allocated block is?
  2385.  
  2386. A:    Unfortunately, there is no standard or portable way.
  2387.  
  2388. 7.30:    Is it legal to pass a null pointer as the first argument to
  2389.     realloc()?  Why would you want to?
  2390.  
  2391. A:    ANSI C sanctions this usage (and the related realloc(..., 0),
  2392.     which frees), although several earlier implementations do not
  2393.     support it, so it may not be fully portable.  Passing an
  2394.     initially-null pointer to realloc() can make it easier to write
  2395.     a self-starting incremental allocation algorithm.
  2396.  
  2397.     References: ISO Sec. 7.10.3.4; H&S Sec. 16.3 p. 388.
  2398.  
  2399. 7.31:    What's the difference between calloc() and malloc()?  Is it safe
  2400.     to take advantage of calloc's zero-filling?  Does free() work
  2401.     on memory allocated with calloc(), or do you need a cfree()?
  2402.  
  2403. A:    calloc(m, n) is essentially equivalent to
  2404.  
  2405.         p = malloc(m * n);
  2406.         memset(p, 0, m * n);
  2407.  
  2408.     The zero fill is all-bits-zero, and does *not* therefore
  2409.     guarantee useful null pointer values (see section 5 of this
  2410.     list) or floating-point zero values.  free() is properly used to
  2411.     free the memory allocated by calloc().
  2412.  
  2413.     References: ISO Sec. 7.10.3 to 7.10.3.2; H&S Sec. 16.1 p. 386,
  2414.     Sec. 16.2 p. 386; PCS Sec. 11 pp. 141,142.
  2415.  
  2416. 7.32:    What is alloca() and why is its use discouraged?
  2417.  
  2418. A:    alloca() allocates memory which is automatically freed when the
  2419.     function which called alloca() returns.  That is, memory
  2420.     allocated with alloca is local to a particular function's "stack
  2421.     frame" or context.
  2422.  
  2423.     alloca() cannot be written portably, and is difficult to
  2424.     implement on machines without a conventional stack.  Its use is
  2425.     problematical (and the obvious implementation on a stack-based
  2426.     machine fails) when its return value is passed directly to
  2427.     another function, as in fgets(alloca(100), 100, stdin).
  2428.  
  2429.     For these reasons, alloca() is not Standard and cannot be used
  2430.     in programs which must be widely portable, no matter how useful
  2431.     it might be.
  2432.  
  2433.     See also question 7.22.
  2434.  
  2435.     References: Rationale Sec. 4.10.3.
  2436.  
  2437.  
  2438. Section 8. Characters and Strings
  2439.  
  2440. 8.1:    Why doesn't
  2441.  
  2442.         strcat(string, '!');
  2443.  
  2444.     work?
  2445.  
  2446. A:    There is a very real difference between characters and strings,
  2447.     and strcat() concatenates *strings*.
  2448.  
  2449.     Characters in C are represented by small integers corresponding
  2450.     to their character set values (see also question 8.6 below).
  2451.     Strings are represented by arrays of characters; you usually
  2452.     manipulate a pointer to the first character of the array.  It is
  2453.     never correct to use one when the other is expected.  To append
  2454.     a ! to a string, use
  2455.  
  2456.         strcat(string, "!");
  2457.  
  2458.     See also questions 1.32, 7.2, and 16.6.
  2459.  
  2460.     References: CT&P Sec. 1.5 pp. 9-10.
  2461.  
  2462. 8.2:    I'm checking a string to see if it matches a particular value.
  2463.     Why isn't this code working?
  2464.  
  2465.         char *string;
  2466.         ...
  2467.         if(string == "value") {
  2468.             /* string matches "value" */
  2469.             ...
  2470.         }
  2471.  
  2472. A:    Strings in C are represented as arrays of characters, and C
  2473.     never manipulates (assigns, compares, etc.) arrays as a whole.
  2474.     The == operator in the code fragment above compares two pointers
  2475.     -- the value of the pointer variable string and a pointer to the
  2476.     string literal "value" -- to see if they are equal, that is, if
  2477.     they point to the same place.  They probably don't, so the
  2478.     comparison never succeeds.
  2479.  
  2480.     To compare two strings, you generally use the library function
  2481.     strcmp():
  2482.  
  2483.         if(strcmp(string, "value") == 0) {
  2484.             /* string matches "value" */
  2485.             ...
  2486.         }
  2487.  
  2488. 8.3:    If I can say
  2489.  
  2490.         char a[] = "Hello, world!";
  2491.  
  2492.     why can't I say
  2493.  
  2494.         char a[14];
  2495.         a = "Hello, world!";
  2496.  
  2497. A:    Strings are arrays, and you can't assign arrays directly.  Use
  2498.     strcpy() instead:
  2499.  
  2500.         strcpy(a, "Hello, world!");
  2501.  
  2502.     See also questions 1.32, 4.2, and 7.2.
  2503.  
  2504. 8.6:    How can I get the numeric (character set) value corresponding to
  2505.     a character, or vice versa?
  2506.  
  2507. A:    In C, characters are represented by small integers corresponding
  2508.     to their values (in the machine's character set), so you don't
  2509.     need a conversion function: if you have the character, you have
  2510.     its value.
  2511.  
  2512. 8.9:    I think something's wrong with my compiler: I just noticed that
  2513.     sizeof('a') is 2, not 1 (i.e. not sizeof(char)).
  2514.  
  2515. A:    Perhaps surprisingly, character constants in C are of type int,
  2516.     so sizeof('a') is sizeof(int) (though this is another area
  2517.     where C++ differs).  See also question 7.8.
  2518.  
  2519.     References: ISO Sec. 6.1.3.4; H&S Sec. 2.7.3 p. 29.
  2520.  
  2521.  
  2522. Section 9. Boolean Expressions and Variables
  2523.  
  2524. 9.1:    What is the right type to use for Boolean values in C?  Why
  2525.     isn't it a standard type?  Should I use #defines or enums for
  2526.     the true and false values?
  2527.  
  2528. A:    C does not provide a standard Boolean type, in part because
  2529.     picking one involves a space/time tradeoff which can best be
  2530.     decided by the programmer.  (Using an int may be faster, while
  2531.     using char may save data space.  Smaller types may make the
  2532.     generated code bigger or slower, though, if they require lots of
  2533.     conversions to and from int.)
  2534.  
  2535.     The choice between #defines and enumeration constants for the
  2536.     true/false values is arbitrary and not terribly interesting (see
  2537.     also questions 2.22 and 17.10).  Use any of
  2538.  
  2539.         #define TRUE  1            #define YES 1
  2540.         #define FALSE 0            #define NO  0
  2541.  
  2542.         enum bool {false, true};    enum bool {no, yes};
  2543.  
  2544.     or use raw 1 and 0, as long as you are consistent within one
  2545.     program or project.  (An enumeration may be preferable if your
  2546.     debugger shows the names of enumeration constants when examining
  2547.     variables.)
  2548.  
  2549.     Some people prefer variants like
  2550.  
  2551.         #define TRUE (1==1)
  2552.         #define FALSE (!TRUE)
  2553.  
  2554.     or define "helper" macros such as
  2555.  
  2556.         #define Istrue(e) ((e) != 0)
  2557.  
  2558.     These don't buy anything (see question 9.2 below; see also
  2559.     questions 5.12 and 10.2).
  2560.  
  2561. 9.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  2562.     is considered "true" in C?  What if a built-in logical or
  2563.     relational operator "returns" something other than 1?
  2564.  
  2565. A:    It is true (sic) that any nonzero value is considered true in C,
  2566.     but this applies only "on input", i.e. where a Boolean value is
  2567.     expected.  When a Boolean value is generated by a built-in
  2568.     operator, it is guaranteed to be 1 or 0.  Therefore, the test
  2569.  
  2570.         if((a == b) == TRUE)
  2571.  
  2572.     would work as expected (as long as TRUE is 1), but it is
  2573.     obviously silly.  In fact, explicit tests against TRUE and
  2574.     FALSE are generally inappropriate, because some library
  2575.     functions (notably isupper(), isalpha(), etc.) return,
  2576.     on success, a nonzero value which is not necessarily 1.
  2577.     (Besides, if you believe that "if((a == b) == TRUE)" is
  2578.     an improvement over "if(a == b)", why stop there?  Why not
  2579.     use "if(((a == b) == TRUE) == TRUE)"?)  A good rule of thumb
  2580.     is to use TRUE and FALSE (or the like) only for assignment
  2581.     to a Boolean variable or function parameter, or as the return
  2582.     value from a Boolean function, but never in a comparison.
  2583.  
  2584.     The preprocessor macros TRUE and FALSE (and, of course, NULL)
  2585.     are used for code readability, not because the underlying values
  2586.     might ever change.  (See also questions 5.3 and 5.10.)
  2587.  
  2588.     Although the use of macros like TRUE and FALSE (or YES
  2589.     and NO) seems clearer, Boolean values and definitions can
  2590.     be sufficiently confusing in C that some programmers feel
  2591.     that TRUE and FALSE macros only compound the confusion, and
  2592.     prefer to use raw 1 and 0 instead.  (See also question 5.9.)
  2593.  
  2594.     References: K&R1 Sec. 2.6 p. 39, Sec. 2.7 p. 41; K&R2 Sec. 2.6
  2595.     p. 42, Sec. 2.7 p. 44, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ISO
  2596.     Sec. 6.3.3.3, Sec. 6.3.8, Sec. 6.3.9, Sec. 6.3.13, Sec. 6.3.14,
  2597.     Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5; H&S Sec. 7.5.4 pp. 196-7,
  2598.     Sec. 7.6.4 pp. 207-8, Sec. 7.6.5 pp. 208-9, Sec. 7.7 pp. 217-8,
  2599.     Sec. 7.8 pp. 218-9, Sec. 8.5 pp. 238-9, Sec. 8.6 pp. 241-4;
  2600.     "What the Tortoise Said to Achilles".
  2601.  
  2602. 9.3:    Is if(p), where p is a pointer, a valid conditional?
  2603.  
  2604. A:    Yes.  See question 5.3.
  2605.  
  2606.  
  2607. Section 10. C Preprocessor
  2608.  
  2609. 10.2:    Here are some cute preprocessor macros:
  2610.  
  2611.         #define begin    {
  2612.         #define end    }
  2613.  
  2614.     What do y'all think?
  2615.  
  2616. A:    Bleah.  See also section 17.
  2617.  
  2618. 10.3:    How can I write a generic macro to swap two values?
  2619.  
  2620. A:    There is no good answer to this question.  If the values are
  2621.     integers, a well-known trick using exclusive-OR could perhaps
  2622.     be used, but it will not work for floating-point values or
  2623.     pointers, or if the two values are the same variable.  (See
  2624.     questions 3.3b and 20.15c.)  If the macro is intended to be
  2625.     used on values of arbitrary type (the usual goal), it cannot
  2626.     use a temporary, since it does not know what type of temporary
  2627.     it needs (and would have a hard time picking a name for it if
  2628.     it did), and standard C does not provide a typeof operator.
  2629.  
  2630.     The best all-around solution is probably to forget about using a
  2631.     macro, unless you're willing to pass in the type as a third
  2632.     argument.
  2633.  
  2634. 10.4:    What's the best way to write a multi-statement macro?
  2635.  
  2636. A:    The usual goal is to write a macro that can be invoked as if it
  2637.     were a statement consisting of a single function call.  This
  2638.     means that the "caller" will be supplying the final semicolon,
  2639.     so the macro body should not.  The macro body cannot therefore
  2640.     be a simple brace-enclosed compound statement, because syntax
  2641.     errors would result if it were invoked (apparently as a single
  2642.     statement, but with a resultant extra semicolon) as the if
  2643.     branch of an if/else statement with an explicit else clause.
  2644.  
  2645.     The traditional solution, therefore, is to use
  2646.  
  2647.         #define MACRO(arg1, arg2) do {    \
  2648.             /* declarations */    \
  2649.             stmt1;            \
  2650.             stmt2;            \
  2651.             /* ... */        \
  2652.             } while(0)    /* (no trailing ; ) */
  2653.  
  2654.     When the caller appends a semicolon, this expansion becomes a
  2655.     single statement regardless of context.  (An optimizing compiler
  2656.     will remove any "dead" tests or branches on the constant
  2657.     condition 0, although lint may complain.)
  2658.  
  2659.     If all of the statements in the intended macro are simple
  2660.     expressions, with no declarations or loops, another technique is
  2661.     to write a single, parenthesized expression using one or more
  2662.     comma operators.  (For an example, see the first DEBUG() macro
  2663.     in question 10.26.)  This technique also allows a value to be
  2664.     "returned."
  2665.  
  2666.     References: H&S Sec. 3.3.2 p. 45; CT&P Sec. 6.3 pp. 82-3.
  2667.  
  2668. 10.6:    I'm splitting up a program into multiple source files for the
  2669.     first time, and I'm wondering what to put in .c files and what
  2670.     to put in .h files.  (What does ".h" mean, anyway?)
  2671.  
  2672. A:    As a general rule, you should put these things in header (.h)
  2673.     files:
  2674.  
  2675.         macro definitions (preprocessor #defines)
  2676.         structure, union, and enumeration declarations
  2677.         typedef declarations
  2678.         external function declarations (see also question 1.11)
  2679.         global variable declarations
  2680.  
  2681.     It's especially important to put a declaration or definition in
  2682.     a header file when it will be shared between several other
  2683.     files.  (In particular, never put external function prototypes
  2684.     in .c files.  See also question 1.7.)
  2685.  
  2686.     On the other hand, when a definition or declaration should
  2687.     remain private to one .c file, it's fine to leave it there.
  2688.  
  2689.     See also questions 1.7 and 10.7.
  2690.  
  2691.     References: K&R2 Sec. 4.5 pp. 81-2; H&S Sec. 9.2.3 p. 267; CT&P
  2692.     Sec. 4.6 pp. 66-7.
  2693.  
  2694. 10.7:    Is it acceptable for one header file to #include another?
  2695.  
  2696. A:    It's a question of style, and thus receives considerable debate.
  2697.     Many people believe that "nested #include files" are to be
  2698.     avoided: the prestigious Indian Hill Style Guide (see question
  2699.     17.9) disparages them; they can make it harder to find relevant
  2700.     definitions; they can lead to multiple-definition errors if a
  2701.     file is #included twice; and they make manual Makefile
  2702.     maintenance very difficult.  On the other hand, they make it
  2703.     possible to use header files in a modular way (a header file can
  2704.     #include what it needs itself, rather than requiring each
  2705.     #includer to do so); a tool like grep (or a tags file) makes it
  2706.     easy to find definitions no matter where they are; a popular
  2707.     trick along the lines of:
  2708.  
  2709.         #ifndef HFILENAME_USED
  2710.         #define HFILENAME_USED
  2711.         ...header file contents...
  2712.         #endif
  2713.  
  2714.     (where a different bracketing macro name is used for each header
  2715.     file) makes a header file "idempotent" so that it can safely be
  2716.     #included multiple times; and automated Makefile maintenance
  2717.     tools (which are a virtual necessity in large projects anyway;
  2718.     see question 18.1) handle dependency generation in the face of
  2719.     nested #include files easily.  See also question 17.10.
  2720.  
  2721.     References: Rationale Sec. 4.1.2.
  2722.  
  2723. 10.8a:    What's the difference between #include <> and #include "" ?
  2724.  
  2725. A:    The <> syntax is typically used with Standard or system-supplied
  2726.     headers, while "" is typically used for a program's own header
  2727.     files.
  2728.  
  2729. 10.8b:    What are the complete rules for header file searching?
  2730.  
  2731. A:    The exact behavior is implementation-defined (which means that
  2732.     it is supposed to be documented; see question 11.33).
  2733.     Typically, headers named with <> syntax are searched for in one
  2734.     or more standard places.  Header files named with "" syntax are
  2735.     first searched for in the "current directory," then (if not
  2736.     found) in the same standard places.
  2737.  
  2738.     Traditionally (especially under Unix compilers), the current
  2739.     directory is taken to be the directory containing the file
  2740.     containing the #include directive.  Under other compilers,
  2741.     however, the current directory (if any) is the directory in
  2742.     which the compiler was initially invoked.  Check your compiler
  2743.     documentation.
  2744.  
  2745.     References: K&R2 Sec. A12.4 p. 231; ISO Sec. 6.8.2; H&S Sec. 3.4
  2746.     p. 55.
  2747.  
  2748. 10.9:    I'm getting strange syntax errors on the very first declaration
  2749.     in a file, but it looks fine.
  2750.  
  2751. A:    Perhaps there's a missing semicolon at the end of the last
  2752.     declaration in the last header file you're #including.  See also
  2753.     questions 2.18, 11.29, and 16.1b.
  2754.  
  2755. 10.10b:    I'm #including the right header file for the library function
  2756.     I'm using, but the linker keeps saying it's undefined.
  2757.  
  2758. A:    See question 13.25.
  2759.  
  2760. 10.11:    I seem to be missing the system header file <sgtty.h>.
  2761.     Can someone send me a copy?
  2762.  
  2763. A:    Standard headers exist in part so that definitions appropriate
  2764.     to your compiler, operating system, and processor can be
  2765.     supplied.  You cannot just pick up a copy of someone else's
  2766.     header file and expect it to work, unless that person is using
  2767.     exactly the same environment.  Ask your compiler vendor why the
  2768.     file was not provided (or to send a replacement copy).
  2769.  
  2770. 10.12:    How can I construct preprocessor #if expressions which compare
  2771.     strings?
  2772.  
  2773. A:    You can't do it directly; preprocessor #if arithmetic uses only
  2774.     integers.  An alternative is to #define several macros with
  2775.     symbolic names and distinct integer values, and implement
  2776.     conditionals on those.
  2777.  
  2778.     See also question 20.17.
  2779.  
  2780.     References: K&R2 Sec. 4.11.3 p. 91; ISO Sec. 6.8.1; H&S
  2781.     Sec. 7.11.1 p. 225.
  2782.  
  2783. 10.13:    Does the sizeof operator work in preprocessor #if directives?
  2784.  
  2785. A:    No.  Preprocessing happens during an earlier phase of
  2786.     compilation, before type names have been parsed.  Instead of
  2787.     sizeof, consider using the predefined constants in ANSI's
  2788.     <limits.h>, if applicable, or perhaps a "configure" script.
  2789.     (Better yet, try to write code which is inherently insensitive
  2790.     to type sizes; see also question 1.1.)
  2791.  
  2792.     References: ISO Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p.
  2793.     225.
  2794.  
  2795. 10.14:    Can I use an #ifdef in a #define line, to define something two
  2796.     different ways?
  2797.  
  2798. A:    No.  You can't "run the preprocessor on itself," so to speak.
  2799.     What you can do is use one of two completely separate #define
  2800.     lines, depending on the #ifdef setting.
  2801.  
  2802.     References: ISO Sec. 6.8.3, Sec. 6.8.3.4; H&S Sec. 3.2 pp. 40-1.
  2803.  
  2804. 10.15:    Is there anything like an #ifdef for typedefs?
  2805.  
  2806. A:    Unfortunately, no.  You may have to keep sets of preprocessor
  2807.     macros (e.g. MY_TYPE_DEFINED) recording whether certain typedefs
  2808.     have been declared.  (See also question 10.13.)
  2809.  
  2810.     References: ISO Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p.
  2811.     225.
  2812.  
  2813. 10.16:    How can I use a preprocessor #if expression to tell if a machine
  2814.     is big-endian or little-endian?
  2815.  
  2816. A:    You probably can't.  (Preprocessor arithmetic uses only long
  2817.     integers, and there is no concept of addressing.)  Are you
  2818.     sure you need to know the machine's endianness explicitly?
  2819.     Usually it's better to write code which doesn't care.
  2820.     See also question 20.9.
  2821.  
  2822.     References: ISO Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.
  2823.  
  2824. 10.18:    I inherited some code which contains far too many #ifdef's for
  2825.     my taste.  How can I preprocess the code to leave only one
  2826.     conditional compilation set, without running it through the
  2827.     preprocessor and expanding all of the #include's and #define's
  2828.     as well?
  2829.  
  2830. A:    There are programs floating around called unifdef, rmifdef,
  2831.     and scpp ("selective C preprocessor") which do exactly this.
  2832.     See question 18.16.
  2833.  
  2834. 10.19:    How can I list all of the predefined identifiers?
  2835.  
  2836. A:    There's no standard way, although it is a common need.  gcc
  2837.     provides a -dM option which works with -E, and other compilers
  2838.     may provide something similar.  If the compiler documentation
  2839.     is unhelpful, the most expedient way is probably to extract
  2840.     printable strings from the compiler or preprocessor executable
  2841.     with something like the Unix strings utility.  Beware that many
  2842.     traditional system-specific predefined identifiers (e.g. "unix")
  2843.     are non-Standard (because they clash with the user's namespace)
  2844.     and are being removed or renamed.
  2845.  
  2846. 10.20:    I have some old code that tries to construct identifiers with a
  2847.     macro like
  2848.  
  2849.         #define Paste(a, b) a/**/b
  2850.  
  2851.     but it doesn't work any more.
  2852.  
  2853. A:    It was an undocumented feature of some early preprocessor
  2854.     implementations (notably John Reiser's) that comments
  2855.     disappeared entirely and could therefore be used for token
  2856.     pasting.  ANSI affirms (as did K&R1) that comments are replaced
  2857.     with white space.  However, since the need for pasting tokens
  2858.     was demonstrated and real, ANSI introduced a well-defined token-
  2859.     pasting operator, ##, which can be used like this:
  2860.  
  2861.         #define Paste(a, b) a##b
  2862.  
  2863.     See also question 11.17.
  2864.  
  2865.     References: ISO Sec. 6.8.3.3; Rationale Sec. 3.8.3.3; H&S
  2866.     Sec. 3.3.9 p. 52.
  2867.  
  2868. 10.22:    Why is the macro
  2869.  
  2870.         #define TRACE(n) printf("TRACE: %d\n", n)
  2871.  
  2872.     giving me the warning "macro replacement within a string
  2873.     literal"?  It seems to be expanding
  2874.  
  2875.         TRACE(count);
  2876.     as
  2877.         printf("TRACE: %d\count", count);
  2878.  
  2879. A:    See question 11.18.
  2880.  
  2881. 10.23-4: I'm having trouble using macro arguments inside string
  2882.     literals, using the `#' operator.
  2883.  
  2884. A:    See questions 11.17 and 11.18.
  2885.  
  2886. 10.25:    I've got this tricky preprocessing I want to do and I can't
  2887.     figure out a way to do it.
  2888.  
  2889. A:    C's preprocessor is not intended as a general-purpose tool.
  2890.     (Note also that it is not guaranteed to be available as a
  2891.     separate program.)  Rather than forcing it to do something
  2892.     inappropriate, consider writing your own little special-purpose
  2893.     preprocessing tool, instead.  You can easily get a utility like
  2894.     make(1) to run it for you automatically.
  2895.  
  2896.     If you are trying to preprocess something other than C, consider
  2897.     using a general-purpose preprocessor.  (One older one available
  2898.     on most Unix systems is m4.)
  2899.  
  2900. 10.26:    How can I write a macro which takes a variable number of
  2901.     arguments?
  2902.  
  2903. A:    One popular trick is to define and invoke the macro with a
  2904.     single, parenthesized "argument" which in the macro expansion
  2905.     becomes the entire argument list, parentheses and all, for a
  2906.     function such as printf():
  2907.  
  2908.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  2909.  
  2910.         if(n != 0) DEBUG(("n is %d\n", n));
  2911.  
  2912.     The obvious disadvantage is that the caller must always remember
  2913.     to use the extra parentheses.
  2914.  
  2915.     gcc has an extension which allows a function-like macro to
  2916.     accept a variable number of arguments, but it's not standard.
  2917.     Other possible solutions are to use different macros (DEBUG1,
  2918.     DEBUG2, etc.) depending on the number of arguments, or to play
  2919.     tricky games with commas:
  2920.  
  2921.         #define DEBUG(args) (printf("DEBUG: "), printf(args))
  2922.         #define _ ,
  2923.  
  2924.         DEBUG("i = %d" _ i)
  2925.  
  2926.     C9X will introduce formal support for function-like macros with
  2927.     variable-length argument lists.  The notation ... will appear at
  2928.     the end of the macro "prototype" (just as it does for varargs
  2929.     functions), and the pseudomacro __VA_ARGS__ in the macro
  2930.     definition will be replaced by the variable arguments during
  2931.     invocation.
  2932.  
  2933.     Finally, you can always use a bona-fide function, which can
  2934.     take a variable number of arguments in a well-defined way.
  2935.     See questions 15.4 and 15.5.  (If you needed a macro
  2936.     replacement, try using a function plus a non-function-like
  2937.     macro, e.g. #define printf myprintf .)
  2938.  
  2939.     References: C9X Sec. 6.8.3, Sec. 6.8.3.1.
  2940.  
  2941.  
  2942. Section 11. ANSI/ISO Standard C
  2943.  
  2944. 11.1:    What is the "ANSI C Standard?"
  2945.  
  2946. A:    In 1983, the American National Standards Institute (ANSI)
  2947.     commissioned a committee, X3J11, to standardize the C language.
  2948.     After a long, arduous process, including several widespread
  2949.     public reviews, the committee's work was finally ratified as ANS
  2950.     X3.159-1989 on December 14, 1989, and published in the spring of
  2951.     1990.    For the most part, ANSI C standardizes existing practice,
  2952.     with a few additions from C++ (most notably function prototypes)
  2953.     and support for multinational character sets (including the
  2954.     controversial trigraph sequences).  The ANSI C standard also
  2955.     formalizes the C run-time library support routines.
  2956.  
  2957.     More recently, the Standard has been adopted as an international
  2958.     standard, ISO/IEC 9899:1990, and this ISO Standard replaces the
  2959.     earlier X3.159 even within the United States (where it is known
  2960.     as ANSI/ISO 9899-1990 [1992]).  As an ISO Standard, it is
  2961.     subject to ongoing revision through the release of Technical
  2962.     Corrigenda and Normative Addenda.
  2963.  
  2964.     In 1994, Technical Corrigendum 1 (TC1) amended the Standard
  2965.     in about 40 places, most of them minor corrections or
  2966.     clarifications, and Normative Addendum 1 (NA1) added about 50
  2967.     pages of new material, mostly specifying new library functions
  2968.     for internationalization.  In 1995, TC2 added a few more minor
  2969.     corrections.
  2970.  
  2971.     As of this writing, a complete revision of the Standard is in
  2972.     its final stages.  The new Standard is nicknamed "C9X" on the
  2973.     assumption that it will be finished by the end of 1999.  (Many
  2974.     of this article's answers have been updated to reflect new C9X
  2975.     features.)
  2976.  
  2977.     The original ANSI Standard included a "Rationale," explaining
  2978.     many of its decisions, and discussing a number of subtle points,
  2979.     including several of those covered here.  (The Rationale was
  2980.     "not part of ANSI Standard X3.159-1989, but... included for
  2981.     information only," and is not included with the ISO Standard.
  2982.     A new one is being prepared for C9X.)
  2983.  
  2984. 11.2:    How can I get a copy of the Standard?
  2985.  
  2986. A:    Copies are available in the United States from
  2987.  
  2988.         American National Standards Institute
  2989.         11 W. 42nd St., 13th floor
  2990.         New York, NY  10036  USA
  2991.         (+1) 212 642 4900
  2992.  
  2993.     and
  2994.  
  2995.         Global Engineering Documents
  2996.         15 Inverness Way E
  2997.         Englewood, CO  80112  USA
  2998.         (+1) 303 397 2715
  2999.         (800) 854 7179  (U.S. & Canada)
  3000.  
  3001.     In other countries, contact the appropriate national standards
  3002.     body, or ISO in Geneva at:
  3003.  
  3004.         ISO Sales
  3005.         Case Postale 56
  3006.         CH-1211 Geneve 20
  3007.         Switzerland
  3008.  
  3009.     (or see URL http://www.iso.ch or check the comp.std.internat FAQ
  3010.     list, Standards.Faq).
  3011.  
  3012.     The last time I checked, the cost was $130.00 from ANSI or
  3013.     $400.50 from Global.  Copies of the original X3.159 (including
  3014.     the Rationale) may still be available at $205.00 from ANSI or
  3015.     $162.50 from Global.  Note that ANSI derives revenues to support
  3016.     its operations from the sale of printed standards, so electronic
  3017.     copies are *not* available.
  3018.  
  3019.     In the U.S., it may be possible to get a copy of the original
  3020.     ANSI X3.159 (including the Rationale) as "FIPS PUB 160" from
  3021.  
  3022.         National Technical Information Service (NTIS)
  3023.         U.S. Department of Commerce
  3024.         Springfield, VA  22161
  3025.         703 487 4650
  3026.  
  3027.     The mistitled _Annotated ANSI C Standard_, with annotations by
  3028.     Herbert Schildt, contains most of the text of ISO 9899; it is
  3029.     published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells
  3030.     in the U.S. for approximately $40.  It has been suggested that
  3031.     the price differential between this work and the official
  3032.     standard reflects the value of the annotations: they are plagued
  3033.     by numerous errors and omissions, and a few pages of the
  3034.     Standard itself are missing.  Many people on the net recommend
  3035.     ignoring the annotations entirely.  A review of the annotations
  3036.     ("annotated annotations") by Clive Feather can be found on the
  3037.     web at http://www.lysator.liu.se/c/schildt.html .
  3038.  
  3039.     The text of the Rationale (not the full Standard) can be
  3040.     obtained by anonymous ftp from ftp.uu.net (see question 18.16)
  3041.     in directory doc/standards/ansi/X3.159-1989, and is also
  3042.     available on the web at http://www.lysator.liu.se/c/rat/title.html .
  3043.     The Rationale has also been printed by Silicon Press,
  3044.     ISBN 0-929306-07-4.
  3045.  
  3046.     Public review drafts of C9X are available from ISO/IEC
  3047.     JTC1/SC22/WG14's web site, http://www.dkuug.dk/JTC1/SC22/WG14/ .
  3048.  
  3049.     See also question 11.2b below.
  3050.  
  3051. 11.2b:    Where can I get information about updates to the Standard?
  3052.  
  3053. A:    You can find information (including C9X drafts) at
  3054.     the web sites http://www.lysator.liu.se/c/index.html,
  3055.     http://www.dkuug.dk/JTC1/SC22/WG14/, and http://www.dmk.com/ .
  3056.  
  3057. 11.3:    My ANSI compiler complains about a mismatch when it sees
  3058.  
  3059.         extern int func(float);
  3060.  
  3061.         int func(x)
  3062.         float x;
  3063.         { ...
  3064.  
  3065. A:    You have mixed the new-style prototype declaration
  3066.     "extern int func(float);" with the old-style definition
  3067.     "int func(x) float x;".  It is usually possible to mix the two
  3068.     styles (see question 11.4), but not in this case.
  3069.  
  3070.     Old C (and ANSI C, in the absence of prototypes, and in variable-
  3071.     length argument lists; see question 15.2) "widens" certain
  3072.     arguments when they are passed to functions.  floats are
  3073.     promoted to double, and characters and short integers are
  3074.     promoted to int.  (For old-style function definitions, the
  3075.     values are automatically converted back to the corresponding
  3076.     narrower types within the body of the called function, if they
  3077.     are declared that way there.)
  3078.  
  3079.     This problem can be fixed either by using new-style syntax
  3080.     consistently in the definition:
  3081.  
  3082.         int func(float x) { ... }
  3083.  
  3084.     or by changing the new-style prototype declaration to match the
  3085.     old-style definition:
  3086.  
  3087.         extern int func(double);
  3088.  
  3089.     (In this case, it would be clearest to change the old-style
  3090.     definition to use double as well, if possible.)
  3091.  
  3092.     It is arguably much safer to avoid "narrow" (char, short int,
  3093.     and float) function arguments and return types altogether.
  3094.  
  3095.     See also question 1.25.
  3096.  
  3097.     References: K&R1 Sec. A7.1 p. 186; K&R2 Sec. A7.3.2 p. 202; ISO
  3098.     Sec. 6.3.2.2, Sec. 6.5.4.3; Rationale Sec. 3.3.2.2,
  3099.     Sec. 3.5.4.3; H&S Sec. 9.2 pp. 265-7, Sec. 9.4 pp. 272-3.
  3100.  
  3101. 11.4:    Can you mix old-style and new-style function syntax?
  3102.  
  3103. A:    Doing so is legal, but requires a certain amount of care (see
  3104.     especially question 11.3).  Modern practice, however, is to
  3105.     use the prototyped form in both declarations and definitions.
  3106.     (The old-style syntax is marked as obsolescent, so official
  3107.     support for it may be removed some day.)
  3108.  
  3109.     References: ISO Sec. 6.7.1, Sec. 6.9.5; H&S Sec. 9.2.2 pp. 265-
  3110.     7, Sec. 9.2.5 pp. 269-70.
  3111.  
  3112. 11.5:    Why does the declaration
  3113.  
  3114.         extern int f(struct x *p);
  3115.  
  3116.     give me an obscure warning message about "struct x introduced in
  3117.     prototype scope"?
  3118.  
  3119. A:    In a quirk of C's normal block scoping rules, a structure
  3120.     declared (or even mentioned) for the first time within a
  3121.     prototype cannot be compatible with other structures declared in
  3122.     the same source file (it goes out of scope at the end of the
  3123.     prototype).
  3124.  
  3125.     To resolve the problem, precede the prototype with the vacuous-
  3126.     looking declaration
  3127.  
  3128.         struct x;
  3129.  
  3130.     which places an (incomplete) declaration of struct x at file
  3131.     scope, so that all following declarations involving struct x can
  3132.     at least be sure they're referring to the same struct x.
  3133.  
  3134.     References: ISO Sec. 6.1.2.1, Sec. 6.1.2.6, Sec. 6.5.2.3.
  3135.  
  3136. 11.8:    I don't understand why I can't use const values in initializers
  3137.     and array dimensions, as in
  3138.  
  3139.         const int n = 5;
  3140.         int a[n];
  3141.  
  3142. A:    The const qualifier really means "read-only"; an object so
  3143.     qualified is a run-time object which cannot (normally) be
  3144.     assigned to.  The value of a const-qualified object is therefore
  3145.     *not* a constant expression in the full sense of the term.  (C
  3146.     is unlike C++ in this regard.)  When you need a true compile-
  3147.     time constant, use a preprocessor #define (or perhaps an enum).
  3148.  
  3149.     References: ISO Sec. 6.4; H&S Secs. 7.11.2,7.11.3 pp. 226-7.
  3150.  
  3151. 11.9:    What's the difference between "const char *p" and
  3152.     "char * const p"?
  3153.  
  3154. A:    "const char *p" (which can also be written "char const *p")
  3155.     declares a pointer to a constant character (you can't change
  3156.     the character); "char * const p" declares a constant pointer
  3157.     to a (variable) character (i.e. you can't change the pointer).
  3158.  
  3159.     Read these "inside out" to understand them; see also question
  3160.     1.21.
  3161.  
  3162.     References: ISO Sec. 6.5.4.1; Rationale Sec. 3.5.4.1; H&S
  3163.     Sec. 4.4.4 p. 81.
  3164.  
  3165. 11.10:    Why can't I pass a char ** to a function which expects a
  3166.     const char **?
  3167.  
  3168. A:    You can use a pointer-to-T (for any type T) where a pointer-to-
  3169.     const-T is expected.  However, the rule (an explicit exception)
  3170.     which permits slight mismatches in qualified pointer types is
  3171.     not applied recursively, but only at the top level.
  3172.  
  3173.     You must use explicit casts (e.g. (const char **) in this case)
  3174.     when assigning (or passing) pointers which have qualifier
  3175.     mismatches at other than the first level of indirection.
  3176.  
  3177.     References: ISO Sec. 6.1.2.6, Sec. 6.3.16.1, Sec. 6.5.3; H&S
  3178.     Sec. 7.9.1 pp. 221-2.
  3179.  
  3180. 11.12a:    What's the correct declaration of main()?
  3181.  
  3182. A:    Either int main(), int main(void), or int main(int argc,
  3183.     char *argv[]) (with alternate spellings of argc and *argv[]
  3184.     obviously allowed).  See also questions 11.12b to 11.15 below.
  3185.  
  3186.     References: ISO Sec. 5.1.2.2.1, Sec. G.5.1; H&S Sec. 20.1 p.
  3187.     416; CT&P Sec. 3.10 pp. 50-51.
  3188.  
  3189. 11.12b:    Can I declare main() as void, to shut off these annoying
  3190.     "main returns no value" messages?
  3191.  
  3192. A:    No.  main() must be declared as returning an int, and as
  3193.     taking either zero or two arguments, of the appropriate types.
  3194.     If you're calling exit() but still getting warnings, you may
  3195.     have to insert a redundant return statement (or use some kind
  3196.     of "not reached" directive, if available).
  3197.  
  3198.     Declaring a function as void does not merely shut off or
  3199.     rearrange warnings: it may also result in a different function
  3200.     call/return sequence, incompatible with what the caller (in
  3201.     main's case, the C run-time startup code) expects.
  3202.  
  3203.     (Note that this discussion of main() pertains only to "hosted"
  3204.     implementations; none of it applies to "freestanding"
  3205.     implementations, which may not even have main().  However,
  3206.     freestanding implementations are comparatively rare, and if
  3207.     you're using one, you probably know it.  If you've never heard
  3208.     of the distinction, you're probably using a hosted
  3209.     implementation, and the above rules apply.)
  3210.  
  3211.     References: ISO Sec. 5.1.2.2.1, Sec. G.5.1; H&S Sec. 20.1 p.
  3212.     416; CT&P Sec. 3.10 pp. 50-51.
  3213.  
  3214. 11.13:    But what about main's third argument, envp?
  3215.  
  3216. A:    It's a non-standard (though common) extension.  If you really
  3217.     need to access the environment in ways beyond what the standard
  3218.     getenv() function provides, though, the global variable environ
  3219.     is probably a better avenue (though it's equally non-standard).
  3220.  
  3221.     References: ISO Sec. G.5.1; H&S Sec. 20.1 pp. 416-7.
  3222.  
  3223. 11.14:    I believe that declaring void main() can't fail, since I'm
  3224.     calling exit() instead of returning, and anyway my operating
  3225.     system ignores a program's exit/return status.
  3226.  
  3227. A:    It doesn't matter whether main() returns or not, or whether
  3228.     anyone looks at the status; the problem is that when main() is
  3229.     misdeclared, its caller (the runtime startup code) may not even
  3230.     be able to *call* it correctly (due to the potential clash of
  3231.     calling conventions; see question 11.12b).
  3232.  
  3233.     It has been reported that programs using void main() and
  3234.     compiled using BC++ 4.5 can crash.  Some compilers (including
  3235.     DEC C V4.1 and gcc with certain warnings enabled) will complain
  3236.     about void main().
  3237.  
  3238.     Your operating system may ignore the exit status, and
  3239.     void main() may work for you, but it is not portable and not
  3240.     correct.
  3241.  
  3242. 11.15:    The book I've been using, _C Programing for the Compleat Idiot_,
  3243.     always uses void main().
  3244.  
  3245. A:    Perhaps its author counts himself among the target audience.
  3246.     Many books unaccountably use void main() in examples, and assert
  3247.     that it's correct.  They're wrong.
  3248.  
  3249. 11.16:    Is exit(status) truly equivalent to returning the same status
  3250.     from main()?
  3251.  
  3252. A:    Yes and no.  The Standard says that they are equivalent.
  3253.     However, a return from main() cannot be expected to work if
  3254.     data local to main() might be needed during cleanup; see also
  3255.     question 16.4.  A few very old, nonconforming systems may once
  3256.     have had problems with one or the other form.  (Finally, the
  3257.     two forms are obviously not equivalent in a recursive call to
  3258.     main().)
  3259.  
  3260.     References: K&R2 Sec. 7.6 pp. 163-4; ISO Sec. 5.1.2.2.3.
  3261.  
  3262. 11.17:    I'm trying to use the ANSI "stringizing" preprocessing operator
  3263.     `#' to insert the value of a symbolic constant into a message,
  3264.     but it keeps stringizing the macro's name rather than its value.
  3265.  
  3266. A:    You can use something like the following two-step procedure to
  3267.     force a macro to be expanded as well as stringized:
  3268.  
  3269.         #define Str(x) #x
  3270.         #define Xstr(x) Str(x)
  3271.         #define OP plus
  3272.         char *opname = Xstr(OP);
  3273.  
  3274.     This code sets opname to "plus" rather than "OP".
  3275.  
  3276.     An equivalent circumlocution is necessary with the token-pasting
  3277.     operator ## when the values (rather than the names) of two
  3278.     macros are to be concatenated.
  3279.  
  3280.     References: ISO Sec. 6.8.3.2, Sec. 6.8.3.5.
  3281.  
  3282. 11.18:    What does the message "warning: macro replacement within a
  3283.     string literal" mean?
  3284.  
  3285. A:    Some pre-ANSI compilers/preprocessors interpreted macro
  3286.     definitions like
  3287.  
  3288.         #define TRACE(var, fmt) printf("TRACE: var = fmt\n", var)
  3289.  
  3290.     such that invocations like
  3291.  
  3292.         TRACE(i, %d);
  3293.  
  3294.     were expanded as
  3295.  
  3296.         printf("TRACE: i = %d\n", i);
  3297.  
  3298.     In other words, macro parameters were expanded even inside
  3299.     string literals and character constants.
  3300.  
  3301.     Macro expansion is *not* defined in this way by K&R or by
  3302.     Standard C.  When you do want to turn macro arguments into
  3303.     strings, you can use the new # preprocessing operator, along
  3304.     with string literal concatenation (another new ANSI feature):
  3305.  
  3306.         #define TRACE(var, fmt) \
  3307.             printf("TRACE: " #var " = " #fmt "\n", var)
  3308.  
  3309.     See also question 11.17 above.
  3310.  
  3311.     References: H&S Sec. 3.3.8 p. 51.
  3312.  
  3313. 11.19:    I'm getting strange syntax errors inside lines I've #ifdeffed
  3314.     out.
  3315.  
  3316. A:    Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  3317.     #ifndef must still consist of "valid preprocessing tokens."
  3318.     This means that the characters " and ' must each be paired just
  3319.     as in real C code, and the pairs mustn't cross line boundaries.
  3320.     (Note particularly that an apostrophe within a contracted word
  3321.     looks like the beginning of a character constant.)  Therefore,
  3322.     natural-language comments and pseudocode should always be
  3323.     written between the "official" comment delimiters /* and */.
  3324.     (But see question 20.20, and also 10.25.)
  3325.  
  3326.     References: ISO Sec. 5.1.1.2, Sec. 6.1; H&S Sec. 3.2 p. 40.
  3327.  
  3328. 11.20:    What are #pragmas and what are they good for?
  3329.  
  3330. A:    The #pragma directive provides a single, well-defined "escape
  3331.     hatch" which can be used for all sorts of (nonportable)
  3332.     implementation-specific controls and extensions: source listing
  3333.     control, structure packing, warning suppression (like lint's old
  3334.     /* NOTREACHED */ comments), etc.
  3335.  
  3336.     References: ISO Sec. 6.8.6; H&S Sec. 3.7 p. 61.
  3337.  
  3338. 11.21:    What does "#pragma once" mean?  I found it in some header files.
  3339.  
  3340. A:    It is an extension implemented by some preprocessors to help
  3341.     make header files idempotent; it is equivalent to the #ifndef
  3342.     trick mentioned in question 10.7, though less portable.
  3343.  
  3344. 11.22:    Is char a[3] = "abc"; legal?  What does it mean?
  3345.  
  3346. A:    It is legal in ANSI C (and perhaps in a few pre-ANSI systems),
  3347.     though useful only in rare circumstances.  It declares an array
  3348.     of size three, initialized with the three characters 'a', 'b',
  3349.     and 'c', *without* the usual terminating '\0' character.  The
  3350.     array is therefore not a true C string and cannot be used with
  3351.     strcpy, printf %s, etc.
  3352.  
  3353.     Most of the time, you should let the compiler count the
  3354.     initializers when initializing arrays (in the case of the
  3355.     initializer "abc", of course, the computed size will be 4).
  3356.  
  3357.     References: ISO Sec. 6.5.7; H&S Sec. 4.6.4 p. 98.
  3358.  
  3359. 11.24:    Why can't I perform arithmetic on a void * pointer?
  3360.  
  3361. A:    The compiler doesn't know the size of the pointed-to objects.
  3362.     Before performing arithmetic, convert the pointer either to
  3363.     char * or to the pointer type you're trying to manipulate (but
  3364.     see also question 4.5).
  3365.  
  3366.     References: ISO Sec. 6.1.2.5, Sec. 6.3.6; H&S Sec. 7.6.2 p. 204.
  3367.  
  3368. 11.25:    What's the difference between memcpy() and memmove()?
  3369.  
  3370. A:    memmove() offers guaranteed behavior if the source and
  3371.     destination arguments overlap.  memcpy() makes no such
  3372.     guarantee, and may therefore be more efficiently implementable.
  3373.     When in doubt, it's safer to use memmove().
  3374.  
  3375.     References: K&R2 Sec. B3 p. 250; ISO Sec. 7.11.2.1,
  3376.     Sec. 7.11.2.2; Rationale Sec. 4.11.2; H&S Sec. 14.3 pp. 341-2;
  3377.     PCS Sec. 11 pp. 165-6.
  3378.  
  3379. 11.26:    What should malloc(0) do?  Return a null pointer or a pointer to
  3380.     0 bytes?
  3381.  
  3382. A:    The ANSI/ISO Standard says that it may do either; the behavior
  3383.     is implementation-defined (see question 11.33).
  3384.  
  3385.     References: ISO Sec. 7.10.3; PCS Sec. 16.1 p. 386.
  3386.  
  3387. 11.27:    Why does the ANSI Standard not guarantee more than six case-
  3388.     insensitive characters of external identifier significance?
  3389.  
  3390. A:    The problem is older linkers which are under the control of
  3391.     neither the ANSI/ISO Standard nor the C compiler developers on
  3392.     the systems which have them.  The limitation is only that
  3393.     identifiers be *significant* in the first six characters, not
  3394.     that they be restricted to six characters in length.  This
  3395.     limitation is marked in the Standard as "obsolescent", and will
  3396.     be removed in C9X.
  3397.  
  3398.     References: ISO Sec. 6.1.2, Sec. 6.9.1; Rationale Sec. 3.1.2;
  3399.     C9X Sec. 6.1.2; H&S Sec. 2.5 pp. 22-3.
  3400.  
  3401. 11.29:    My compiler is rejecting the simplest possible test programs,
  3402.     with all kinds of syntax errors.
  3403.  
  3404. A:    Perhaps it is a pre-ANSI compiler, unable to accept function
  3405.     prototypes and the like.
  3406.  
  3407.     See also questions 1.31, 10.9, 11.30, and 16.1b.
  3408.  
  3409. 11.30:    Why are some ANSI/ISO Standard library functions showing up as
  3410.     undefined, even though I've got an ANSI compiler?
  3411.  
  3412. A:    It's possible to have a compiler available which accepts ANSI
  3413.     syntax, but not to have ANSI-compatible header files or run-time
  3414.     libraries installed.  (In fact, this situation is rather common
  3415.     when using a non-vendor-supplied compiler such as gcc.)  See
  3416.     also questions 11.29, 13.25, and 13.26.
  3417.  
  3418. 11.31:    Does anyone have a tool for converting old-style C programs to
  3419.     ANSI C, or vice versa, or for automatically generating
  3420.     prototypes?
  3421.  
  3422. A:    Two programs, protoize and unprotoize, convert back and forth
  3423.     between prototyped and "old style" function definitions and
  3424.     declarations.  (These programs do *not* handle full-blown
  3425.     translation between "Classic" C and ANSI C.)  These programs are
  3426.     part of the FSF's GNU C compiler distribution; see question
  3427.     18.3.
  3428.  
  3429.     The unproto program (/pub/unix/unproto5.shar.Z on
  3430.     ftp.win.tue.nl) is a filter which sits between the preprocessor
  3431.     and the next compiler pass, converting most of ANSI C to
  3432.     traditional C on-the-fly.
  3433.  
  3434.     The GNU GhostScript package comes with a little program called
  3435.     ansi2knr.
  3436.  
  3437.     Before converting ANSI C back to old-style, beware that such a
  3438.     conversion cannot always be made both safely and automatically.
  3439.     ANSI C introduces new features and complexities not found in K&R
  3440.     C.  You'll especially need to be careful of prototyped function
  3441.     calls; you'll probably need to insert explicit casts.  See also
  3442.     questions 11.3 and 11.29.
  3443.  
  3444.     Several prototype generators exist, many as modifications to
  3445.     lint.  A program called CPROTO was posted to comp.sources.misc
  3446.     in March, 1992.  There is another program called "cextract."
  3447.     Many vendors supply simple utilities like these with their
  3448.     compilers.  See also question 18.16.  (But be careful when
  3449.     generating prototypes for old functions with "narrow"
  3450.     parameters; see question 11.3.)
  3451.  
  3452. 11.32:    Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  3453.     compliant, accept this code?  I know that the code is ANSI,
  3454.     because gcc accepts it.
  3455.  
  3456. A:    Many compilers support a few non-Standard extensions, gcc more
  3457.     so than most.  Are you sure that the code being rejected doesn't
  3458.     rely on such an extension?  It is usually a bad idea to perform
  3459.     experiments with a particular compiler to determine properties
  3460.     of a language; the applicable standard may permit variations, or
  3461.     the compiler may be wrong.  See also question 11.35.
  3462.  
  3463. 11.33:    People seem to make a point of distinguishing between
  3464.     implementation-defined, unspecified, and undefined behavior.
  3465.     What's the difference?
  3466.  
  3467. A:    Briefly: implementation-defined means that an implementation
  3468.     must choose some behavior and document it.  Unspecified means
  3469.     that an implementation should choose some behavior, but need not
  3470.     document it.  Undefined means that absolutely anything might
  3471.     happen.  In no case does the Standard impose requirements; in
  3472.     the first two cases it occasionally suggests (and may require a
  3473.     choice from among) a small set of likely behaviors.
  3474.  
  3475.     Note that since the Standard imposes *no* requirements on the
  3476.     behavior of a compiler faced with an instance of undefined
  3477.     behavior, the compiler can do absolutely anything.  In
  3478.     particular, there is no guarantee that the rest of the program
  3479.     will perform normally.  It's perilous to think that you can
  3480.     tolerate undefined behavior in a program; see question 3.2 for a
  3481.     relatively simple example.
  3482.  
  3483.     If you're interested in writing portable code, you can ignore
  3484.     the distinctions, as you'll want to avoid code that depends on
  3485.     any of the three behaviors.
  3486.  
  3487.     See also questions 3.9, and 11.34.
  3488.  
  3489.     References: ISO Sec. 3.10, Sec. 3.16, Sec. 3.17; Rationale
  3490.     Sec. 1.6.
  3491.  
  3492. 11.34:    I'm appalled that the ANSI Standard leaves so many issues
  3493.     undefined.  Isn't a Standard's whole job to standardize these
  3494.     things?
  3495.  
  3496. A:    It has always been a characteristic of C that certain constructs
  3497.     behaved in whatever way a particular compiler or a particular
  3498.     piece of hardware chose to implement them.  This deliberate
  3499.     imprecision often allows compilers to generate more efficient
  3500.     code for common cases, without having to burden all programs
  3501.     with extra code to assure well-defined behavior of cases deemed
  3502.     to be less reasonable.  Therefore, the Standard is simply
  3503.     codifying existing practice.
  3504.  
  3505.     A programming language standard can be thought of as a treaty
  3506.     between the language user and the compiler implementor.  Parts
  3507.     of that treaty consist of features which the compiler
  3508.     implementor agrees to provide, and which the user may assume
  3509.     will be available.  Other parts, however, consist of rules which
  3510.     the user agrees to follow and which the implementor may assume
  3511.     will be followed.  As long as both sides uphold their
  3512.     guarantees, programs have a fighting chance of working
  3513.     correctly.  If *either* side reneges on any of its commitments,
  3514.     nothing is guaranteed to work.
  3515.  
  3516.     See also question 11.35.
  3517.  
  3518.     References: Rationale Sec. 1.1.
  3519.  
  3520. 11.35:    People keep saying that the behavior of i = i++ is undefined,
  3521.     but I just tried it on an ANSI-conforming compiler, and got the
  3522.     results I expected.
  3523.  
  3524. A:    A compiler may do anything it likes when faced with undefined
  3525.     behavior (and, within limits, with implementation-defined and
  3526.     unspecified behavior), including doing what you expect.  It's
  3527.     unwise to depend on it, though.  See also questions 11.32,
  3528.     11.33, and 11.34.
  3529.  
  3530.  
  3531. Section 12. Stdio
  3532.  
  3533. 12.1:    What's wrong with this code?
  3534.  
  3535.         char c;
  3536.         while((c = getchar()) != EOF) ...
  3537.  
  3538. A:    For one thing, the variable to hold getchar's return value must
  3539.     be an int.  getchar() can return all possible character values,
  3540.     as well as EOF.  By squeezing getchar's return value into a
  3541.     char, either a normal character might be misinterpreted as EOF,
  3542.     or the EOF might be altered (particularly if type char is
  3543.     unsigned) and so never seen.
  3544.  
  3545.     References: K&R1 Sec. 1.5 p. 14; K&R2 Sec. 1.5.1 p. 16; ISO
  3546.     Sec. 6.1.2.5, Sec. 7.9.1, Sec. 7.9.7.5; H&S Sec. 5.1.3 p. 116,
  3547.     Sec. 15.1, Sec. 15.6; CT&P Sec. 5.1 p. 70; PCS Sec. 11 p. 157.
  3548.  
  3549. 12.2:    Why does the code
  3550.  
  3551.         while(!feof(infp)) {
  3552.             fgets(buf, MAXLINE, infp);
  3553.             fputs(buf, outfp);
  3554.         }
  3555.  
  3556.     copy the last line twice?
  3557.  
  3558. A:    In C, end-of-file is only indicated *after* an input routine has
  3559.     tried to read, and failed.  (In other words, C's I/O is not like
  3560.     Pascal's.)  Usually, you should just check the return value of
  3561.     the input routine (in this case, fgets() will return NULL on end-
  3562.     of-file); often, you don't need to use feof() at all.
  3563.  
  3564.     References: K&R2 Sec. 7.6 p. 164; ISO Sec. 7.9.3, Sec. 7.9.7.1,
  3565.     Sec. 7.9.10.2; H&S Sec. 15.14 p. 382.
  3566.  
  3567. 12.4:    My program's prompts and intermediate output don't always show
  3568.     up on the screen, especially when I pipe the output through
  3569.     another program.
  3570.  
  3571. A:    It's best to use an explicit fflush(stdout) whenever output
  3572.     should definitely be visible (and especially if the text does
  3573.     not end with \n).  Several mechanisms attempt to perform the
  3574.     fflush() for you, at the "right time," but they tend to apply
  3575.     only when stdout is an interactive terminal.  (See also question
  3576.     12.24.)
  3577.  
  3578.     References: ISO Sec. 7.9.5.2.
  3579.  
  3580. 12.5:    How can I read one character at a time, without waiting for the
  3581.     RETURN key?
  3582.  
  3583. A:    See question 19.1.
  3584.  
  3585. 12.6:    How can I print a '%' character in a printf format string?  I
  3586.     tried \%, but it didn't work.
  3587.  
  3588. A:    Simply double the percent sign: %% .
  3589.  
  3590.     \% can't work, because the backslash \ is the *compiler's*
  3591.     escape character, while here our problem is that the % is
  3592.     essentially printf's escape character.
  3593.  
  3594.     See also question 19.17.
  3595.  
  3596.     References: K&R1 Sec. 7.3 p. 147; K&R2 Sec. 7.2 p. 154; ISO
  3597.     Sec. 7.9.6.1.
  3598.  
  3599. 12.9:    Someone told me it was wrong to use %lf with printf().  How can
  3600.     printf() use %f for type double, if scanf() requires %lf?
  3601.  
  3602. A:    It's true that printf's %f specifier works with both float and
  3603.     double arguments.  Due to the "default argument promotions"
  3604.     (which apply in variable-length argument lists such as
  3605.     printf's, whether or not prototypes are in scope), values of
  3606.     type float are promoted to double, and printf() therefore sees
  3607.     only doubles.  (printf() does accept %Lf, for long double.)
  3608.     See also questions 12.13 and 15.2.
  3609.  
  3610.     References: K&R1 Sec. 7.3 pp. 145-47, Sec. 7.4 pp. 147-50; K&R2
  3611.     Sec. 7.2 pp. 153-44, Sec. 7.4 pp. 157-59; ISO Sec. 7.9.6.1,
  3612.     Sec. 7.9.6.2; H&S Sec. 15.8 pp. 357-64, Sec. 15.11 pp. 366-78;
  3613.     CT&P Sec. A.1 pp. 121-33.
  3614.  
  3615. 12.9b:    What printf format should I use for a typedef like size_t
  3616.     when I don't know whether it's long or some other type?
  3617.  
  3618. A:    Use a cast to convert the value to a known, conservatively-
  3619.     sized type, then use the printf format matching that type.
  3620.     For example, to print the size of a type, you might use
  3621.  
  3622.         printf("%lu", (unsigned long)sizeof(thetype));
  3623.  
  3624. 12.10:    How can I implement a variable field width with printf?
  3625.     That is, instead of %8d, I want the width to be specified
  3626.     at run time.
  3627.  
  3628. A:    printf("%*d", width, x) will do just what you want.
  3629.     See also question 12.15.
  3630.  
  3631.     References: K&R1 Sec. 7.3; K&R2 Sec. 7.2; ISO Sec. 7.9.6.1; H&S
  3632.     Sec. 15.11.6; CT&P Sec. A.1.
  3633.  
  3634. 12.11:    How can I print numbers with commas separating the thousands?
  3635.     What about currency formatted numbers?
  3636.  
  3637. A:    The functions in <locale.h> begin to provide some support for
  3638.     these operations, but there is no standard routine for doing
  3639.     either task.  (The only thing printf() does in response to a
  3640.     custom locale setting is to change its decimal-point character.)
  3641.  
  3642.     References: ISO Sec. 7.4; H&S Sec. 11.6 pp. 301-4.
  3643.  
  3644. 12.12:    Why doesn't the call scanf("%d", i) work?
  3645.  
  3646. A:    The arguments you pass to scanf() must always be pointers.
  3647.     To fix the fragment above, change it to scanf("%d", &i) .
  3648.  
  3649. 12.13:    Why doesn't this code:
  3650.  
  3651.         double d;
  3652.         scanf("%f", &d);
  3653.  
  3654.     work?
  3655.  
  3656. A:    Unlike printf(), scanf() uses %lf for values of type double, and
  3657.     %f for float.  See also question 12.9.
  3658.  
  3659. 12.15:    How can I specify a variable width in a scanf() format string?
  3660.  
  3661. A:    You can't; an asterisk in a scanf() format string means to
  3662.     suppress assignment.  You may be able to use ANSI stringizing
  3663.     and string concatenation to accomplish about the same thing, or
  3664.     you can construct the scanf format string at run time.
  3665.  
  3666. 12.17:    When I read numbers from the keyboard with scanf "%d\n", it
  3667.     seems to hang until I type one extra line of input.
  3668.  
  3669. A:    Perhaps surprisingly, \n in a scanf format string does *not*
  3670.     mean to expect a newline, but rather to read and discard
  3671.     characters as long as each is a whitespace character.
  3672.     See also question 12.20.
  3673.  
  3674.     References: K&R2 Sec. B1.3 pp. 245-6; ISO Sec. 7.9.6.2; H&S
  3675.     Sec. 15.8 pp. 357-64.
  3676.  
  3677. 12.18:    I'm reading a number with scanf %d and then a string with
  3678.     gets(), but the compiler seems to be skipping the call to
  3679.     gets()!
  3680.  
  3681. A:    scanf %d won't consume a trailing newline.  If the input number
  3682.     is immediately followed by a newline, that newline will
  3683.     immediately satisfy the gets().
  3684.  
  3685.     As a general rule, you shouldn't try to interlace calls to
  3686.     scanf() with calls to gets() (or any other input routines);
  3687.     scanf's peculiar treatment of newlines almost always leads to
  3688.     trouble.  Either use scanf() to read everything or nothing.
  3689.  
  3690.     See also questions 12.20 and 12.23.
  3691.  
  3692.     References: ISO Sec. 7.9.6.2; H&S Sec. 15.8 pp. 357-64.
  3693.  
  3694. 12.19:    I figured I could use scanf() more safely if I checked its
  3695.     return value to make sure that the user typed the numeric values
  3696.     I expect, but sometimes it seems to go into an infinite loop.
  3697.  
  3698. A:    When scanf() is attempting to convert numbers, any non-numeric
  3699.     characters it encounters terminate the conversion *and are left
  3700.     on the input stream*.  Therefore, unless some other steps are
  3701.     taken, unexpected non-numeric input "jams" scanf() again and
  3702.     again: scanf() never gets past the bad character(s) to encounter
  3703.     later, valid data.  If the user types a character like `x' in
  3704.     response to a numeric scanf format such as %d or %f, code that
  3705.     simply re-prompts and retries the same scanf() call will
  3706.     immediately reencounter the same `x'.
  3707.  
  3708.     See also question 12.20.
  3709.  
  3710.     References: ISO Sec. 7.9.6.2; H&S Sec. 15.8 pp. 357-64.
  3711.  
  3712. 12.20:    Why does everyone say not to use scanf()?  What should I use
  3713.     instead?
  3714.  
  3715. A:    scanf() has a number of problems -- see questions 12.17, 12.18,
  3716.     and 12.19.  Also, its %s format has the same problem that gets()
  3717.     has (see question 12.23) -- it's hard to guarantee that the
  3718.     receiving buffer won't overflow.
  3719.  
  3720.     More generally, scanf() is designed for relatively structured,
  3721.     formatted input (its name is in fact derived from "scan
  3722.     formatted").  If you pay attention, it will tell you whether it
  3723.     succeeded or failed, but it can tell you only approximately
  3724.     where it failed, and not at all how or why.  It's nearly
  3725.     impossible to do decent error recovery with scanf(); usually
  3726.     it's far easier to read entire lines (with fgets() or the like),
  3727.     then interpret them, either using sscanf() or some other
  3728.     techniques.  (Functions like strtol(), strtok(), and atoi() are
  3729.     often useful; see also question 13.6.)  If you do use any scanf
  3730.     variant, be sure to check the return value to make sure that the
  3731.     expected number of items were found.  Also, if you use %s, be
  3732.     sure to guard against buffer overflow.
  3733.  
  3734.     References: K&R2 Sec. 7.4 p. 159.
  3735.  
  3736. 12.21:    How can I tell how much destination buffer space I'll need for
  3737.     an arbitrary sprintf call?  How can I avoid overflowing the
  3738.     destination buffer with sprintf()?
  3739.  
  3740. A:    When the format string being used with sprintf() is known and
  3741.     relatively simple, you can sometimes predict a buffer size in an
  3742.     ad-hoc way.  If the format consists of one or two %s's, you can
  3743.     count the fixed characters in the format string yourself (or let
  3744.     sizeof count them for you) and add in the result of calling
  3745.     strlen() on the string(s) to be inserted.  For integers, the
  3746.     number of characters produced by %d is no more than
  3747.  
  3748.         ((sizeof(int) * CHAR_BIT + 2) / 3 + 1)  /* +1 for '-' */
  3749.  
  3750.     (CHAR_BIT is in <limits.h>), though this computation may be over-
  3751.     conservative.  (It computes the number of characters required
  3752.     for a base-8 representation of a number; a base-10 expansion is
  3753.     guaranteed to take as much room or less.)
  3754.  
  3755.     When the format string is more complicated, or is not even known
  3756.     until run time, predicting the buffer size becomes as difficult
  3757.     as reimplementing sprintf(), and correspondingly error-prone
  3758.     (and inadvisable).  A last-ditch technique which is sometimes
  3759.     suggested is to use fprintf() to print the same text to a bit
  3760.     bucket or temporary file, and then to look at fprintf's return
  3761.     value or the size of the file (but see question 19.12, and worry
  3762.     about write errors).
  3763.  
  3764.     If there's any chance that the buffer might not be big enough,
  3765.     you won't want to call sprintf() without some guarantee that the
  3766.     buffer will not overflow and overwrite some other part of
  3767.     memory.  If the format string is known, you can limit %s
  3768.     expansion by using %.Ns for some N, or %.*s (see also question
  3769.     12.10).
  3770.  
  3771.     The "obvious" solution to the overflow problem is a length-
  3772.     limited version of sprintf(), namely snprintf().  It would be
  3773.     used like this:
  3774.  
  3775.         snprintf(buf, bufsize, "You typed \"%s\"", answer);
  3776.  
  3777.     snprintf() has been available in several stdio libraries
  3778.     (including GNU and 4.4bsd) for several years.  It will be
  3779.     standardized in C9X.
  3780.  
  3781.     When the C9X snprintf() arrives, it will also be possible to use
  3782.     it to predict the size required for an arbitrary sprintf() call.
  3783.     C9X snprintf() will return the number of characters it would
  3784.     have placed in the buffer, not just how many it did place.
  3785.     Furthermore, it may be called with a buffer size of 0 and a
  3786.     null pointer as the destination buffer.  Therefore, the call
  3787.  
  3788.         nch = snprintf(NULL, 0, fmtstring, /* other arguments */ );
  3789.  
  3790.     will compute the number of characters required for the fully-
  3791.     formatted string.
  3792.  
  3793.     References: C9X Sec. 7.13.6.6.
  3794.  
  3795. 12.23:    Why does everyone say not to use gets()?
  3796.  
  3797. A:    Unlike fgets(), gets() cannot be told the size of the buffer
  3798.     it's to read into, so it cannot be prevented from overflowing
  3799.     that buffer.  As a general rule, always use fgets().  See
  3800.     question 7.1 for a code fragment illustrating the replacement of
  3801.     gets() with fgets().
  3802.  
  3803.     References: Rationale Sec. 4.9.7.2; H&S Sec. 15.7 p. 356.
  3804.  
  3805. 12.24:    Why does errno contain ENOTTY after a call to printf()?
  3806.  
  3807. A:    Many implementations of the stdio package adjust their behavior
  3808.     slightly if stdout is a terminal.  To make the determination,
  3809.     these implementations perform some operation which happens to
  3810.     fail (with ENOTTY) if stdout is not a terminal.  Although the
  3811.     output operation goes on to complete successfully, errno still
  3812.     contains ENOTTY.  (Note that it is only meaningful for a program
  3813.     to inspect the contents of errno after an error has been
  3814.     reported; errno is not guaranteed to be 0 otherwise.)
  3815.  
  3816.     References: ISO Sec. 7.1.4, Sec. 7.9.10.3; CT&P Sec. 5.4 p. 73;
  3817.     PCS Sec. 14 p. 254.
  3818.  
  3819. 12.25:    What's the difference between fgetpos/fsetpos and ftell/fseek?
  3820.     What are fgetpos() and fsetpos() good for?
  3821.  
  3822. A:    ftell() and fseek() use type long int to represent offsets
  3823.     (positions) in a file, and may therefore be limited to offsets
  3824.     of about 2 billion (2**31-1).  The newer fgetpos() and fsetpos()
  3825.     functions, on the other hand, use a special typedef, fpos_t, to
  3826.     represent the offsets.  The type behind this typedef, if chosen
  3827.     appropriately, can represent arbitrarily large offsets, so
  3828.     fgetpos() and fsetpos() can be used with arbitrarily huge files.
  3829.     fgetpos() and fsetpos() also record the state associated with
  3830.     multibyte streams.  See also question 1.4.
  3831.  
  3832.     References: K&R2 Sec. B1.6 p. 248; ISO Sec. 7.9.1,
  3833.     Secs. 7.9.9.1,7.9.9.3; H&S Sec. 15.5 p. 252.
  3834.  
  3835. 12.26:    How can I flush pending input so that a user's typeahead isn't
  3836.     read at the next prompt?  Will fflush(stdin) work?
  3837.  
  3838. A:    fflush() is defined only for output streams.  Since its
  3839.     definition of "flush" is to complete the writing of buffered
  3840.     characters (not to discard them), discarding unread input would
  3841.     not be an analogous meaning for fflush on input streams.
  3842.  
  3843.     There is no standard way to discard unread characters from a
  3844.     stdio input stream, nor would such a way necessarily be
  3845.     sufficient, since unread characters can also accumulate in
  3846.     other, OS-level input buffers.  You may be able to read and
  3847.     discard characters until \n, or use the curses flushinp()
  3848.     function, or use some system-specific technique.  See also
  3849.     questions 19.1 and 19.2.
  3850.  
  3851.     References: ISO Sec. 7.9.5.2; H&S Sec. 15.2.
  3852.  
  3853. 12.30:    I'm trying to update a file in place, by using fopen mode "r+",
  3854.     reading a certain string, and writing back a modified string,
  3855.     but it's not working.
  3856.  
  3857. A:    Be sure to call fseek before you write, both to seek back to the
  3858.     beginning of the string you're trying to overwrite, and because
  3859.     an fseek or fflush is always required between reading and
  3860.     writing in the read/write "+" modes.  Also, remember that you
  3861.     can only overwrite characters with the same number of
  3862.     replacement characters, and that overwriting in text mode may
  3863.     truncate the file at that point.  See also question 19.14.
  3864.  
  3865.     References: ISO Sec. 7.9.5.3.
  3866.  
  3867. 12.33:    How can I redirect stdin or stdout to a file from within a
  3868.     program?
  3869.  
  3870. A:    Use freopen() (but see question 12.34 below).
  3871.  
  3872.     References: ISO Sec. 7.9.5.4; H&S Sec. 15.2.
  3873.  
  3874. 12.34:    Once I've used freopen(), how can I get the original stdout (or
  3875.     stdin) back?
  3876.  
  3877. A:    There isn't a good way.  If you need to switch back, the best
  3878.     solution is not to have used freopen() in the first place.  Try
  3879.     using your own explicit output (or input) stream variable, which
  3880.     you can reassign at will, while leaving the original stdout (or
  3881.     stdin) undisturbed.
  3882.  
  3883.     It is barely possible to save away information about a stream
  3884.     before calling freopen(), such that the original stream can
  3885.     later be restored, but the methods involve system-specific calls
  3886.     such as dup(), or copying or inspecting the contents of a FILE
  3887.     structure, which is exceedingly nonportable and unreliable.
  3888.  
  3889. 12.36b:    How can I arrange to have output go two places at once,
  3890.     e.g. to the screen and to a file?
  3891.  
  3892. A:    You can't do this directly, but you could write your
  3893.     own printf variant which printed everything twice.
  3894.     See question 15.5.
  3895.  
  3896. 12.38:    How can I read a binary data file properly?  I'm occasionally
  3897.     seeing 0x0a and 0x0d values getting garbled, and I seem to hit
  3898.     EOF prematurely if the data contains the value 0x1a.
  3899.  
  3900. A:    When you're reading a binary data file, you should specify "rb"
  3901.     mode when calling fopen(), to make sure that text file
  3902.     translations do not occur.  Similarly, when writing binary data
  3903.     files, use "wb".
  3904.  
  3905.     Note that the text/binary distinction is made when you open the
  3906.     file: once a file is open, it doesn't matter which I/O calls you
  3907.     use on it.  See also question 20.5.
  3908.  
  3909.     References: ISO Sec. 7.9.5.3; H&S Sec. 15.2.1 p. 348.
  3910.  
  3911.  
  3912. Section 13. Library Functions
  3913.  
  3914. 13.1:    How can I convert numbers to strings (the opposite of atoi)?
  3915.     Is there an itoa() function?
  3916.  
  3917. A:    Just use sprintf().  (Don't worry that sprintf() may be
  3918.     overkill, potentially wasting run time or code space; it works
  3919.     well in practice.)  See the examples in the answer to question
  3920.     7.5a; see also question 12.21.
  3921.  
  3922.     You can obviously use sprintf() to convert long or floating-
  3923.     point numbers to strings as well (using %ld or %f).
  3924.  
  3925.     References: K&R1 Sec. 3.6 p. 60; K&R2 Sec. 3.6 p. 64.
  3926.  
  3927. 13.2:    Why does strncpy() not always place a '\0' terminator in the
  3928.     destination string?
  3929.  
  3930. A:    strncpy() was first designed to handle a now-obsolete data
  3931.     structure, the fixed-length, not-necessarily-\0-terminated
  3932.     "string."  (A related quirk of strncpy's is that it pads short
  3933.     strings with multiple \0's, out to the specified length.)
  3934.     strncpy() is admittedly a bit cumbersome to use in other
  3935.     contexts, since you must often append a '\0' to the destination
  3936.     string by hand.  You can get around the problem by using
  3937.     strncat() instead of strncpy(): if the destination string starts
  3938.     out empty, strncat() does what you probably wanted strncpy() to
  3939.     do.  Another possibility is sprintf(dest, "%.*s", n, source) .
  3940.  
  3941.     When arbitrary bytes (as opposed to strings) are being copied,
  3942.     memcpy() is usually a more appropriate function to use than
  3943.     strncpy().
  3944.  
  3945. 13.5:    Why do some versions of toupper() act strangely if given an
  3946.     upper-case letter?
  3947.     Why does some code call islower() before toupper()?
  3948.  
  3949. A:    Older versions of toupper() and tolower() did not always work
  3950.     correctly on arguments which did not need converting (i.e. on
  3951.     digits or punctuation or letters already of the desired case).
  3952.     In ANSI/ISO Standard C, these functions are guaranteed to work
  3953.     appropriately on all character arguments.
  3954.  
  3955.     References: ISO Sec. 7.3.2; H&S Sec. 12.9 pp. 320-1; PCS p. 182.
  3956.  
  3957. 13.6:    How can I split up a string into whitespace-separated fields?
  3958.     How can I duplicate the process by which main() is handed argc
  3959.     and argv?
  3960.  
  3961. A:    The only Standard function available for this kind of
  3962.     "tokenizing" is strtok(), although it can be tricky to use and
  3963.     it may not do everything you want it to.  (For instance, it does
  3964.     not handle quoting.)
  3965.  
  3966.     References: K&R2 Sec. B3 p. 250; ISO Sec. 7.11.5.8; H&S
  3967.     Sec. 13.7 pp. 333-4; PCS p. 178.
  3968.  
  3969. 13.7:    I need some code to do regular expression and wildcard matching.
  3970.  
  3971. A:    Make sure you recognize the difference between classic regular
  3972.     expressions (variants of which are used in such Unix utilities
  3973.     as ed and grep), and filename wildcards (variants of which are
  3974.     used by most operating systems).
  3975.  
  3976.     There are a number of packages available for matching regular
  3977.     expressions.  Most packages use a pair of functions, one for
  3978.     "compiling" the regular expression, and one for "executing" it
  3979.     (i.e. matching strings against it).  Look for header files named
  3980.     <regex.h> or <regexp.h>, and functions called regcmp/regex,
  3981.     regcomp/regexec, or re_comp/re_exec.  (These functions may
  3982.     exist in a separate regexp library.)  A popular, freely-
  3983.     redistributable regexp package by Henry Spencer is available
  3984.     from ftp.cs.toronto.edu in pub/regexp.shar.Z or in several other
  3985.     archives.  The GNU project has a package called rx.  See also
  3986.     question 18.16.
  3987.  
  3988.     Filename wildcard matching (sometimes called "globbing") is done
  3989.     in a variety of ways on different systems.  On Unix, wildcards
  3990.     are automatically expanded by the shell before a process is
  3991.     invoked, so programs rarely have to worry about them explicitly.
  3992.     Under MS-DOS compilers, there is often a special object file
  3993.     which can be linked in to a program to expand wildcards while
  3994.     argv is being built.  Several systems (including MS-DOS and VMS)
  3995.     provide system services for listing or opening files specified
  3996.     by wildcards.  Check your compiler/library documentation.  See
  3997.     also questions 19.20 and 20.3.
  3998.  
  3999. 13.8:    I'm trying to sort an array of strings with qsort(), using
  4000.     strcmp() as the comparison function, but it's not working.
  4001.  
  4002. A:    By "array of strings" you probably mean "array of pointers to
  4003.     char."  The arguments to qsort's comparison function are
  4004.     pointers to the objects being sorted, in this case, pointers to
  4005.     pointers to char.  strcmp(), however, accepts simple pointers to
  4006.     char.  Therefore, strcmp() can't be used directly.  Write an
  4007.     intermediate comparison function like this:
  4008.  
  4009.         /* compare strings via pointers */
  4010.         int pstrcmp(const void *p1, const void *p2)
  4011.         {
  4012.             return strcmp(*(char * const *)p1, *(char * const *)p2);
  4013.         }
  4014.  
  4015.     The comparison function's arguments are expressed as "generic
  4016.     pointers," const void *.  They are converted back to what they
  4017.     "really are" (pointers to pointers to char) and dereferenced,
  4018.     yielding char *'s which can be passed to strcmp().
  4019.  
  4020.     (Don't be misled by the discussion in K&R2 Sec. 5.11 pp. 119-20,
  4021.     which is not discussing the Standard library's qsort).
  4022.  
  4023.     References: ISO Sec. 7.10.5.2; H&S Sec. 20.5 p. 419.
  4024.  
  4025. 13.9:    Now I'm trying to sort an array of structures with qsort().  My
  4026.     comparison function takes pointers to structures, but the
  4027.     compiler complains that the function is of the wrong type for
  4028.     qsort().  How can I cast the function pointer to shut off the
  4029.     warning?
  4030.  
  4031. A:    The conversions must be in the comparison function, which must
  4032.     be declared as accepting "generic pointers" (const void *) as
  4033.     discussed in question 13.8 above.  The comparison function might
  4034.     look like
  4035.  
  4036.         int mystructcmp(const void *p1, const void *p2)
  4037.         {
  4038.             const struct mystruct *sp1 = p1;
  4039.             const struct mystruct *sp2 = p2;
  4040.             /* now compare sp1->whatever and sp2-> ... */
  4041.  
  4042.     (The conversions from generic pointers to struct mystruct
  4043.     pointers happen in the initializations sp1 = p1 and sp2 = p2;
  4044.     the compiler performs the conversions implicitly since p1 and p2
  4045.     are void pointers.)
  4046.  
  4047.     If, on the other hand, you're sorting pointers to structures,
  4048.     you'll need indirection, as in question 13.8:
  4049.     sp1 = *(struct mystruct * const *)p1 .
  4050.  
  4051.     In general, it is a bad idea to insert casts just to "shut the
  4052.     compiler up."  Compiler warnings are usually trying to tell you
  4053.     something, and unless you really know what you're doing, you
  4054.     ignore or muzzle them at your peril.  See also question 4.9.
  4055.  
  4056.     References: ISO Sec. 7.10.5.2; H&S Sec. 20.5 p. 419.
  4057.  
  4058. 13.10:    How can I sort a linked list?
  4059.  
  4060. A:    Sometimes it's easier to keep the list in order as you build it
  4061.     (or perhaps to use a tree instead).  Algorithms like insertion
  4062.     sort and merge sort lend themselves ideally to use with linked
  4063.     lists.  If you want to use a standard library function, you can
  4064.     allocate a temporary array of pointers, fill it in with pointers
  4065.     to all your list nodes, call qsort(), and finally rebuild the
  4066.     list pointers based on the sorted array.
  4067.  
  4068.     References: Knuth Sec. 5.2.1 pp. 80-102, Sec. 5.2.4 pp. 159-168;
  4069.     Sedgewick Sec. 8 pp. 98-100, Sec. 12 pp. 163-175.
  4070.  
  4071. 13.11:    How can I sort more data than will fit in memory?
  4072.  
  4073. A:    You want an "external sort," which you can read about in Knuth,
  4074.     Volume 3.  The basic idea is to sort the data in chunks (as much
  4075.     as will fit in memory at one time), write each sorted chunk to a
  4076.     temporary file, and then merge the files.  Your operating system
  4077.     may provide a general-purpose sort utility, and if so, you can
  4078.     try invoking it from within your program: see questions 19.27
  4079.     and 19.30.
  4080.  
  4081.     References: Knuth Sec. 5.4 pp. 247-378; Sedgewick Sec. 13 pp.
  4082.     177-187.
  4083.  
  4084. 13.12:    How can I get the current date or time of day in a C program?
  4085.  
  4086. A:    Just use the time(), ctime(), localtime() and/or strftime()
  4087.     functions.  Here is a simple example:
  4088.  
  4089.         #include <stdio.h>
  4090.         #include <time.h>
  4091.  
  4092.         int main()
  4093.         {
  4094.             time_t now;
  4095.             time(&now);
  4096.             printf("It's %.24s.\n", ctime(&now));
  4097.             return 0;
  4098.         }
  4099.  
  4100.     References: K&R2 Sec. B10 pp. 255-7; ISO Sec. 7.12; H&S Sec. 18.
  4101.  
  4102. 13.13:    I know that the library function localtime() will convert a
  4103.     time_t into a broken-down struct tm, and that ctime() will
  4104.     convert a time_t to a printable string.  How can I perform the
  4105.     inverse operations of converting a struct tm or a string into a
  4106.     time_t?
  4107.  
  4108. A:    ANSI C specifies a library function, mktime(), which converts a
  4109.     struct tm to a time_t.
  4110.  
  4111.     Converting a string to a time_t is harder, because of the wide
  4112.     variety of date and time formats which might be encountered.
  4113.     Some systems provide a strptime() function, which is basically
  4114.     the inverse of strftime().  Other popular functions are partime()
  4115.     (widely distributed with the RCS package) and getdate() (and a
  4116.     few others, from the C news distribution).  See question 18.16.
  4117.  
  4118.     References: K&R2 Sec. B10 p. 256; ISO Sec. 7.12.2.3; H&S
  4119.     Sec. 18.4 pp. 401-2.
  4120.  
  4121. 13.14:    How can I add N days to a date?  How can I find the difference
  4122.     between two dates?
  4123.  
  4124. A:    The ANSI/ISO Standard C mktime() and difftime() functions
  4125.     provide some support for both problems.  mktime() accepts non-
  4126.     normalized dates, so it is straightforward to take a filled-in
  4127.     struct tm, add or subtract from the tm_mday field, and call
  4128.     mktime() to normalize the year, month, and day fields (and
  4129.     incidentally convert to a time_t value).  difftime() computes
  4130.     the difference, in seconds, between two time_t values; mktime()
  4131.     can be used to compute time_t values for two dates to be
  4132.     subtracted.
  4133.  
  4134.     These solutions are only guaranteed to work correctly for dates
  4135.     in the range which can be represented as time_t's.  The tm_mday
  4136.     field is an int, so day offsets of more than 32,736 or so may
  4137.     cause overflow.  Note also that at daylight saving time
  4138.     changeovers, local days are not 24 hours long (so don't assume
  4139.     that division by 86400 will be exact).
  4140.  
  4141.     Another approach to both problems is to use "Julian day
  4142.     numbers".  Code for handling Julian day numbers can be found
  4143.     in the Snippets collection (see question 18.15c), the
  4144.     Simtel/Oakland archives (file JULCAL10.ZIP, see question 18.16),
  4145.     and the "Date conversions" article mentioned in the References.
  4146.  
  4147.     See also questions 13.13, 20.31, and 20.32.
  4148.  
  4149.     References: K&R2 Sec. B10 p. 256; ISO Secs. 7.12.2.2,7.12.2.3;
  4150.     H&S Secs. 18.4,18.5 pp. 401-2; David Burki, "Date Conversions".
  4151.  
  4152. 13.14b:    Does C have any Year 2000 problems?
  4153.  
  4154. A:    No, although poorly-written C programs do.
  4155.  
  4156.     The tm_year field of struct tm holds the value of the year minus
  4157.     1900; this field will therefore contain the value 100 for the
  4158.     year 2000.  Code that uses tm_year correctly (by adding or
  4159.     subtracting 1900 when converting to or from human-readable
  4160.     4-digit year representations) will have no problems at the turn
  4161.     of the millennium.  Any code that uses tm_year incorrectly,
  4162.     however, such as by using it directly as a human-readable
  4163.     2-digit year, or setting it from a 4-digit year with code like
  4164.  
  4165.         tm.tm_year = yyyy % 100;    /* WRONG */
  4166.  
  4167.     or printing it as an allegedly human-readable 4-digit year with
  4168.     code like
  4169.  
  4170.         printf("19%d", tm.tm_year);    /* WRONG */
  4171.  
  4172.     will have grave y2k problems indeed.  See also question 20.32.
  4173.  
  4174.     References: K&R2 Sec. B10 p. 255; ISO Sec. 7.12.1; H&S Sec. 18.4
  4175.     p. 401.
  4176.  
  4177. 13.15:    I need a random number generator.
  4178.  
  4179. A:    The Standard C library has one: rand().  The implementation on
  4180.     your system may not be perfect, but writing a better one isn't
  4181.     necessarily easy, either.
  4182.  
  4183.     If you do find yourself needing to implement your own random
  4184.     number generator, there is plenty of literature out there; see
  4185.     the References.  There are also any number of packages on the
  4186.     net: look for r250, RANLIB, and FSULTRA (see question 18.16).
  4187.  
  4188.     References: K&R2 Sec. 2.7 p. 46, Sec. 7.8.7 p. 168; ISO
  4189.     Sec. 7.10.2.1; H&S Sec. 17.7 p. 393; PCS Sec. 11 p. 172; Knuth
  4190.     Vol. 2 Chap. 3 pp. 1-177; Park and Miller, "Random Number
  4191.     Generators: Good Ones are Hard to Find".
  4192.  
  4193. 13.16:    How can I get random integers in a certain range?
  4194.  
  4195. A:    The obvious way,
  4196.  
  4197.         rand() % N        /* POOR */
  4198.  
  4199.     (which tries to return numbers from 0 to N-1) is poor, because
  4200.     the low-order bits of many random number generators are
  4201.     distressingly *non*-random.  (See question 13.18.)  A better
  4202.     method is something like
  4203.  
  4204.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  4205.  
  4206.     If you're worried about using floating point, you could use
  4207.  
  4208.         rand() / (RAND_MAX / N + 1)
  4209.  
  4210.     Both methods obviously require knowing RAND_MAX (which ANSI
  4211.     #defines in <stdlib.h>), and assume that N is much less than
  4212.     RAND_MAX.
  4213.  
  4214.     (Note, by the way, that RAND_MAX is a *constant* telling you
  4215.     what the fixed range of the C library rand() function is.  You
  4216.     cannot set RAND_MAX to some other value, and there is no way of
  4217.     requesting that rand() return numbers in some other range.)
  4218.  
  4219.     If you're starting with a random number generator which returns
  4220.     floating-point values between 0 and 1, all you have to do to get
  4221.     integers from 0 to N-1 is multiply the output of that generator
  4222.     by N.
  4223.  
  4224.     References: K&R2 Sec. 7.8.7 p. 168; PCS Sec. 11 p. 172.
  4225.  
  4226. 13.17:    Each time I run my program, I get the same sequence of numbers
  4227.     back from rand().
  4228.  
  4229. A:    You can call srand() to seed the pseudo-random number generator
  4230.     with a truly random initial value.  Popular seed values are the
  4231.     time of day, or the elapsed time before the user presses a key
  4232.     (although keypress times are hard to determine portably; see
  4233.     question 19.37).  (Note also that it's rarely useful to call
  4234.     srand() more than once during a run of a program; in particular,
  4235.     don't try calling srand() before each call to rand(), in an
  4236.     attempt to get "really random" numbers.)
  4237.  
  4238.     References: K&R2 Sec. 7.8.7 p. 168; ISO Sec. 7.10.2.2; H&S
  4239.     Sec. 17.7 p. 393.
  4240.  
  4241. 13.18:    I need a random true/false value, so I'm just taking rand() % 2,
  4242.     but it's alternating 0, 1, 0, 1, 0...
  4243.  
  4244. A:    Poor pseudorandom number generators (such as the ones
  4245.     unfortunately supplied with some systems) are not very random in
  4246.     the low-order bits.  Try using the higher-order bits: see
  4247.     question 13.16.
  4248.  
  4249.     References: Knuth Sec. 3.2.1.1 pp. 12-14.
  4250.  
  4251. 13.20:    How can I generate random numbers with a normal or Gaussian
  4252.     distribution?
  4253.  
  4254. A:    Here is one method, recommended by Knuth and due originally to
  4255.     Marsaglia:
  4256.  
  4257.         #include <stdlib.h>
  4258.         #include <math.h>
  4259.  
  4260.         double gaussrand()
  4261.         {
  4262.             static double V1, V2, S;
  4263.             static int phase = 0;
  4264.             double X;
  4265.  
  4266.             if(phase == 0) {
  4267.                 do {
  4268.                     double U1 = (double)rand() / RAND_MAX;
  4269.                     double U2 = (double)rand() / RAND_MAX;
  4270.  
  4271.                     V1 = 2 * U1 - 1;
  4272.                     V2 = 2 * U2 - 1;
  4273.                     S = V1 * V1 + V2 * V2;
  4274.                     } while(S >= 1 || S == 0);
  4275.  
  4276.                 X = V1 * sqrt(-2 * log(S) / S);
  4277.             } else
  4278.                 X = V2 * sqrt(-2 * log(S) / S);
  4279.  
  4280.             phase = 1 - phase;
  4281.  
  4282.             return X;
  4283.         }
  4284.  
  4285.     See the extended versions of this list (see question 20.40) for
  4286.     other ideas.
  4287.  
  4288.     References: Knuth Sec. 3.4.1 p. 117; Marsaglia and Bray,
  4289.     "A Convenient Method for Generating Normal Variables";
  4290.     Press et al., _Numerical Recipes in C_ Sec. 7.2 pp. 288-290.
  4291.  
  4292. 13.24:    I'm trying to port this         A:    Those functions are variously
  4293.     old program.  Why do I        obsolete; you should
  4294.     get "undefined external"    instead:
  4295.     errors for:
  4296.  
  4297.     index?                use strchr.
  4298.     rindex?                use strrchr.
  4299.     bcopy?                use memmove, after
  4300.                     interchanging the first and
  4301.                     second arguments (see also
  4302.                     question 11.25).
  4303.     bcmp?                use memcmp.
  4304.     bzero?                use memset, with a second
  4305.                     argument of 0.
  4306.  
  4307.     References: PCS Sec. 11.
  4308.  
  4309. 13.25:    I keep getting errors due to library functions being undefined,
  4310.     but I'm #including all the right header files.
  4311.  
  4312. A:    In general, a header file contains only declarations.  In some
  4313.     cases (especially if the functions are nonstandard) obtaining
  4314.     the actual *definitions* may require explicitly asking for the
  4315.     correct libraries to be searched when you link the program.
  4316.     (#including the header doesn't do that.)  See also questions
  4317.     11.30, 13.26, and 14.3.
  4318.  
  4319. 13.26:    I'm still getting errors due to library functions being
  4320.     undefined, even though I'm explicitly requesting the right
  4321.     libraries while linking.
  4322.  
  4323. A:    Many linkers make one pass over the list of object files and
  4324.     libraries you specify, and extract from libraries only those
  4325.     modules which satisfy references which have so far come up as
  4326.     undefined.  Therefore, the order in which libraries are listed
  4327.     with respect to object files (and each other) is significant;
  4328.     usually, you want to search the libraries last.  (For example,
  4329.     under Unix, put any -l options towards the end of the command
  4330.     line.)  See also question 13.28.
  4331.  
  4332. 13.28:    What does it mean when the linker says that _end is undefined?
  4333.  
  4334. A:    That message is a quirk of the old Unix linkers.  You get an
  4335.     error about _end being undefined only when other symbols are
  4336.     undefined, too -- fix the others, and the error about _end will
  4337.     disappear.  (See also questions 13.25 and 13.26.)
  4338.  
  4339.  
  4340. Section 14. Floating Point
  4341.  
  4342. 14.1:    When I set a float variable to, say, 3.1, why is printf printing
  4343.     it as 3.0999999?
  4344.  
  4345. A:    Most computers use base 2 for floating-point numbers as well as
  4346.     for integers.  In base 2, one divided by ten is an infinitely-
  4347.     repeating fraction (0.0001100110011...), so fractions such as
  4348.     3.1 (which look like they can be exactly represented in decimal)
  4349.     cannot be represented exactly in binary.  Depending on how
  4350.     carefully your compiler's binary/decimal conversion routines
  4351.     (such as those used by printf) have been written, you may see
  4352.     discrepancies when numbers (especially low-precision floats) not
  4353.     exactly representable in base 2 are assigned or read in and then
  4354.     printed (i.e. converted from base 10 to base 2 and back again).
  4355.     See also question 14.6.
  4356.  
  4357. 14.2:    I'm trying to take some square roots, but I'm getting crazy
  4358.     numbers.
  4359.  
  4360. A:    Make sure that you have #included <math.h>, and correctly
  4361.     declared other functions returning double.  (Another library
  4362.     function to be careful with is atof(), which is declared in
  4363.     <stdlib.h>.)  See also question 14.3 below.
  4364.  
  4365.     References: CT&P Sec. 4.5 pp. 65-6.
  4366.  
  4367. 14.3:    I'm trying to do some simple trig, and I am #including <math.h>,
  4368.     but I keep getting "undefined: sin" compilation errors.
  4369.  
  4370. A:    Make sure you're actually linking with the math library.  For
  4371.     instance, under Unix, you usually need to use the -lm option, at
  4372.     the *end* of the command line, when compiling/linking.  See also
  4373.     questions 13.25, 13.26, and 14.2.
  4374.  
  4375. 14.4:    My floating-point calculations are acting strangely and giving
  4376.     me different answers on different machines.
  4377.  
  4378. A:    First, see question 14.2 above.
  4379.  
  4380.     If the problem isn't that simple, recall that digital computers
  4381.     usually use floating-point formats which provide a close but by
  4382.     no means exact simulation of real number arithmetic.  Underflow,
  4383.     cumulative precision loss, and other anomalies are often
  4384.     troublesome.
  4385.  
  4386.     Don't assume that floating-point results will be exact, and
  4387.     especially don't assume that floating-point values can be
  4388.     compared for equality.  (Don't throw haphazard "fuzz factors"
  4389.     in, either; see question 14.5.)
  4390.  
  4391.     These problems are no worse for C than they are for any other
  4392.     computer language.  Certain aspects of floating-point are
  4393.     usually defined as "however the processor does them" (see also
  4394.     question 11.34), otherwise a compiler for a machine without the
  4395.     "right" model would have to do prohibitively expensive
  4396.     emulations.
  4397.  
  4398.     This article cannot begin to list the pitfalls associated with,
  4399.     and workarounds appropriate for, floating-point work.  A good
  4400.     numerical programming text should cover the basics; see also the
  4401.     references below.
  4402.  
  4403.     References: Kernighan and Plauger, _The Elements of Programming
  4404.     Style_ Sec. 6 pp. 115-8; Knuth, Volume 2 chapter 4; David
  4405.     Goldberg, "What Every Computer Scientist Should Know about
  4406.     Floating-Point Arithmetic".
  4407.  
  4408. 14.5:    What's a good way to check for "close enough" floating-point
  4409.     equality?
  4410.  
  4411. A:    Since the absolute accuracy of floating point values varies, by
  4412.     definition, with their magnitude, the best way of comparing two
  4413.     floating point values is to use an accuracy threshold which is
  4414.     relative to the magnitude of the numbers being compared.  Rather
  4415.     than
  4416.  
  4417.         double a, b;
  4418.         ...
  4419.         if(a == b)    /* WRONG */
  4420.  
  4421.     use something like
  4422.  
  4423.         #include <math.h>
  4424.  
  4425.         if(fabs(a - b) <= epsilon * fabs(a))
  4426.  
  4427.     for some suitably-chosen degree of closeness epsilon (as long as
  4428.     a is nonzero!).
  4429.  
  4430.     References: Knuth Sec. 4.2.2 pp. 217-8.
  4431.  
  4432. 14.6:    How do I round numbers?
  4433.  
  4434. A:    The simplest and most straightforward way is with code like
  4435.  
  4436.         (int)(x + 0.5)
  4437.  
  4438.     This technique won't work properly for negative numbers,
  4439.     though (for which you could use something like
  4440.     (int)(x < 0 ? x - 0.5 : x + 0.5)).
  4441.  
  4442. 14.7:    Why doesn't C have an exponentiation operator?
  4443.  
  4444. A:    Because few processors have an exponentiation instruction.
  4445.     C has a pow() function, declared in <math.h>, although explicit
  4446.     multiplication is usually better for small positive integral
  4447.     exponents.
  4448.  
  4449.     References: ISO Sec. 7.5.5.1; H&S Sec. 17.6 p. 393.
  4450.  
  4451. 14.8:    The predefined constant M_PI seems to be missing from my
  4452.     machine's copy of <math.h>.
  4453.  
  4454. A:    That constant (which is apparently supposed to be the value of
  4455.     pi, accurate to the machine's precision), is not standard.  If
  4456.     you need pi, you'll have to define it yourself, or compute it
  4457.     with 4*atan(1.0).
  4458.  
  4459.     References: PCS Sec. 13 p. 237.
  4460.  
  4461. 14.9:    How do I test for IEEE NaN and other special values?
  4462.  
  4463. A:    Many systems with high-quality IEEE floating-point
  4464.     implementations provide facilities (e.g. predefined constants,
  4465.     and functions like isnan(), either as nonstandard extensions in
  4466.     <math.h> or perhaps in <ieee.h> or <nan.h>) to deal with these
  4467.     values cleanly, and work is being done to formally standardize
  4468.     such facilities.  A crude but usually effective test for NaN is
  4469.     exemplified by
  4470.  
  4471.         #define isnan(x) ((x) != (x))
  4472.  
  4473.     although non-IEEE-aware compilers may optimize the test away.
  4474.  
  4475.     C9X will provide isnan(), fpclassify(), and several other
  4476.     classification routines.
  4477.  
  4478.     Another possibility is to to format the value in question using
  4479.     sprintf(): on many systems it generates strings like "NaN" and
  4480.     "Inf" which you could compare for in a pinch.
  4481.  
  4482.     See also question 19.39.
  4483.  
  4484.     References: C9X Sec. 7.7.3.
  4485.  
  4486. 14.11:    What's a good way to implement complex numbers in C?
  4487.  
  4488. A:    It is straightforward to define a simple structure and some
  4489.     arithmetic functions to manipulate them.  C9X will support
  4490.     complex as a standard type.  See also questions 2.7, 2.10, and
  4491.     14.12.
  4492.  
  4493.     References: C9X Sec. 6.1.2.5, Sec. 7.8.
  4494.  
  4495. 14.12:    I'm looking for some code to do:
  4496.         Fast Fourier Transforms (FFT's)
  4497.         matrix arithmetic (multiplication, inversion, etc.)
  4498.         complex arithmetic
  4499.  
  4500. A:    Ajay Shah has prepared a nice index of free numerical
  4501.     software which has been archived pretty widely; one URL
  4502.     is ftp://ftp.math.psu.edu/pub/FAQ/numcomp-free-c .
  4503.     See also questions 18.13, 18.15c, and 18.16.
  4504.  
  4505. 14.13:    I'm having trouble with a Turbo C program which crashes and says
  4506.     something like "floating point formats not linked."
  4507.  
  4508. A:    Some compilers for small machines, including Borland's
  4509.     (and Ritchie's original PDP-11 compiler), leave out certain
  4510.     floating point support if it looks like it will not be needed.
  4511.     In particular, the non-floating-point versions of printf()
  4512.     and scanf() save space by not including code to handle %e, %f,
  4513.     and %g.  It happens that Borland's heuristics for determining
  4514.     whether the program uses floating point are insufficient,
  4515.     and the programmer must sometimes insert a dummy call to a
  4516.     floating-point library function (such as sqrt(); any will
  4517.     do) to force loading of floating-point support.  (See the
  4518.     comp.os.msdos.programmer FAQ list for more information.)
  4519.  
  4520.  
  4521. Section 15. Variable-Length Argument Lists
  4522.  
  4523. 15.1:    I heard that you have to #include <stdio.h> before calling
  4524.     printf().  Why?
  4525.  
  4526. A:    So that a proper prototype for printf() will be in scope.
  4527.  
  4528.     A compiler may use a different calling sequence for functions
  4529.     which accept variable-length argument lists.  (It might do so if
  4530.     calls using variable-length argument lists were less efficient
  4531.     than those using fixed-length.)  Therefore, a prototype
  4532.     (indicating, using the ellipsis notation "...", that the
  4533.     argument list is of variable length) must be in scope whenever a
  4534.     varargs function is called, so that the compiler knows to use
  4535.     the varargs calling mechanism.
  4536.  
  4537.     References: ISO Sec. 6.3.2.2, Sec. 7.1.7; Rationale
  4538.     Sec. 3.3.2.2, Sec. 4.1.6; H&S Sec. 9.2.4 pp. 268-9, Sec. 9.6 pp.
  4539.     275-6.
  4540.  
  4541. 15.2:    How can %f be used for both float and double arguments in
  4542.     printf()?  Aren't they different types?
  4543.  
  4544. A:    In the variable-length part of a variable-length argument list,
  4545.     the "default argument promotions" apply: types char and
  4546.     short int are promoted to int, and float is promoted to double.
  4547.     (These are the same promotions that apply to function calls
  4548.     without a prototype in scope, also known as "old style" function
  4549.     calls; see question 11.3.)  Therefore, printf's %f format always
  4550.     sees a double.  (Similarly, %c always sees an int, as does %hd.)
  4551.     See also questions 12.9 and 12.13.
  4552.  
  4553.     References: ISO Sec. 6.3.2.2; H&S Sec. 6.3.5 p. 177, Sec. 9.4
  4554.     pp. 272-3.
  4555.  
  4556. 15.3:    I had a frustrating problem which turned out to be caused by the
  4557.     line
  4558.  
  4559.         printf("%d", n);
  4560.  
  4561.     where n was actually a long int.  I thought that ANSI function
  4562.     prototypes were supposed to guard against argument type
  4563.     mismatches like this.
  4564.  
  4565. A:    When a function accepts a variable number of arguments, its
  4566.     prototype does not (and cannot) provide any information about
  4567.     the number and types of those variable arguments.  Therefore,
  4568.     the usual protections do *not* apply in the variable-length part
  4569.     of variable-length argument lists: the compiler cannot perform
  4570.     implicit conversions or (in general) warn about mismatches.
  4571.  
  4572.     See also questions 5.2, 11.3, 12.9, and 15.2.
  4573.  
  4574. 15.4:    How can I write a function that takes a variable number of
  4575.     arguments?
  4576.  
  4577. A:    Use the facilities of the <stdarg.h> header.
  4578.  
  4579.     Here is a function which concatenates an arbitrary number of
  4580.     strings into malloc'ed memory:
  4581.  
  4582.         #include <stdlib.h>        /* for malloc, NULL, size_t */
  4583.         #include <stdarg.h>        /* for va_ stuff */
  4584.         #include <string.h>        /* for strcat et al. */
  4585.  
  4586.         char *vstrcat(char *first, ...)
  4587.         {
  4588.             size_t len;
  4589.             char *retbuf;
  4590.             va_list argp;
  4591.             char *p;
  4592.  
  4593.             if(first == NULL)
  4594.                 return NULL;
  4595.  
  4596.             len = strlen(first);
  4597.  
  4598.             va_start(argp, first);
  4599.  
  4600.             while((p = va_arg(argp, char *)) != NULL)
  4601.                 len += strlen(p);
  4602.  
  4603.             va_end(argp);
  4604.  
  4605.             retbuf = malloc(len + 1);    /* +1 for trailing \0 */
  4606.  
  4607.             if(retbuf == NULL)
  4608.                 return NULL;        /* error */
  4609.  
  4610.             (void)strcpy(retbuf, first);
  4611.  
  4612.             va_start(argp, first);        /* restart; 2nd scan */
  4613.  
  4614.             while((p = va_arg(argp, char *)) != NULL)
  4615.                 (void)strcat(retbuf, p);
  4616.  
  4617.             va_end(argp);
  4618.  
  4619.             return retbuf;
  4620.         }
  4621.  
  4622.     Usage is something like
  4623.  
  4624.         char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  4625.  
  4626.     Note the cast on the last argument; see questions 5.2 and 15.3.
  4627.     (Also note that the caller must free the returned, malloc'ed
  4628.     storage.)
  4629.  
  4630.     See also question 15.7.
  4631.  
  4632.     References: K&R2 Sec. 7.3 p. 155, Sec. B7 p. 254; ISO Sec. 7.8;
  4633.     Rationale Sec. 4.8; H&S Sec. 11.4 pp. 296-9; CT&P Sec. A.3 pp.
  4634.     139-141; PCS Sec. 11 pp. 184-5, Sec. 13 p. 242.
  4635.  
  4636. 15.5:    How can I write a function that takes a format string and a
  4637.     variable number of arguments, like printf(), and passes them to
  4638.     printf() to do most of the work?
  4639.  
  4640. A:    Use vprintf(), vfprintf(), or vsprintf().
  4641.  
  4642.     Here is an error() function which prints an error message,
  4643.     preceded by the string "error: " and terminated with a newline:
  4644.  
  4645.         #include <stdio.h>
  4646.         #include <stdarg.h>
  4647.  
  4648.         void error(char *fmt, ...)
  4649.         {
  4650.             va_list argp;
  4651.             fprintf(stderr, "error: ");
  4652.             va_start(argp, fmt);
  4653.             vfprintf(stderr, fmt, argp);
  4654.             va_end(argp);
  4655.             fprintf(stderr, "\n");
  4656.         }
  4657.  
  4658.     See also question 15.7.
  4659.  
  4660.     References: K&R2 Sec. 8.3 p. 174, Sec. B1.2 p. 245; ISO
  4661.     Secs. 7.9.6.7,7.9.6.8,7.9.6.9; H&S Sec. 15.12 pp. 379-80; PCS
  4662.     Sec. 11 pp. 186-7.
  4663.  
  4664. 15.6:    How can I write a function analogous to scanf(), that calls
  4665.     scanf() to do most of the work?
  4666.  
  4667. A:    C9X will support vscanf(), vfscanf(), and vsscanf().
  4668.     (Until then, you may be on your own.)
  4669.  
  4670.     References: C9X Secs. 7.3.6.12-14.
  4671.  
  4672. 15.7:    I have a pre-ANSI compiler, without <stdarg.h>.  What can I do?
  4673.  
  4674. A:    There's an older header, <varargs.h>, which offers about the
  4675.     same functionality.
  4676.  
  4677.     References: H&S Sec. 11.4 pp. 296-9; CT&P Sec. A.2 pp. 134-139;
  4678.     PCS Sec. 11 pp. 184-5, Sec. 13 p. 250.
  4679.  
  4680. 15.8:    How can I discover how many arguments a function was actually
  4681.     called with?
  4682.  
  4683. A:    This information is not available to a portable program.  Some
  4684.     old systems provided a nonstandard nargs() function, but its use
  4685.     was always questionable, since it typically returned the number
  4686.     of words passed, not the number of arguments.  (Structures, long
  4687.     ints, and floating point values are usually passed as several
  4688.     words.)
  4689.  
  4690.     Any function which takes a variable number of arguments must be
  4691.     able to determine *from the arguments themselves* how many of
  4692.     them there are.  printf-like functions do this by looking for
  4693.     formatting specifiers (%d and the like) in the format string
  4694.     (which is why these functions fail badly if the format string
  4695.     does not match the argument list).  Another common technique,
  4696.     applicable when the arguments are all of the same type, is to
  4697.     use a sentinel value (often 0, -1, or an appropriately-cast null
  4698.     pointer) at the end of the list (see the execl() and vstrcat()
  4699.     examples in questions 5.2 and 15.4).  Finally, if their types
  4700.     are predictable, you can pass an explicit count of the number of
  4701.     variable arguments (although it's usually a nuisance for the
  4702.     caller to supply).
  4703.  
  4704.     References: PCS Sec. 11 pp. 167-8.
  4705.  
  4706. 15.9:    My compiler isn't letting me declare a function
  4707.  
  4708.         int f(...)
  4709.         {
  4710.         }
  4711.  
  4712.     i.e. with no fixed arguments.
  4713.  
  4714. A:    Standard C requires at least one fixed argument, in part so that
  4715.     you can hand it to va_start().  See also question 15.10.
  4716.  
  4717.     References: ISO Sec. 6.5.4, Sec. 6.5.4.3, Sec. 7.8.1.1; H&S
  4718.     Sec. 9.2 p. 263.
  4719.  
  4720. 15.10:    I have a varargs function which accepts a float parameter.  Why
  4721.     isn't
  4722.  
  4723.         va_arg(argp, float)
  4724.  
  4725.     working?
  4726.  
  4727. A:    In the variable-length part of variable-length argument lists,
  4728.     the old "default argument promotions" apply: arguments of type
  4729.     float are always promoted (widened) to type double, and types
  4730.     char and short int are promoted to int.  Therefore, it is never
  4731.     correct to invoke va_arg(argp, float); instead you should always
  4732.     use va_arg(argp, double).  Similarly, use va_arg(argp, int) to
  4733.     retrieve arguments which were originally char, short, or int.
  4734.     (For analogous reasons, the last "fixed" argument, as handed to
  4735.     va_start(), should not be widenable, either.)  See also
  4736.     questions 11.3 and 15.2.
  4737.  
  4738.     References: ISO Sec. 6.3.2.2; Rationale Sec. 4.8.1.2; H&S
  4739.     Sec. 11.4 p. 297.
  4740.  
  4741. 15.11:    I can't get va_arg() to pull in an argument of type pointer-to-
  4742.     function.
  4743.  
  4744. A:    The type-rewriting games which the va_arg() macro typically
  4745.     plays are stymied by overly-complicated types such as pointer-to-
  4746.     function.  If you use a typedef for the function pointer type,
  4747.     however, all will be well.  See also question 1.21.
  4748.  
  4749.     References: ISO Sec. 7.8.1.2; Rationale Sec. 4.8.1.2.
  4750.  
  4751. 15.12:    How can I write a function which takes a variable number of
  4752.     arguments and passes them to some other function (which takes a
  4753.     variable number of arguments)?
  4754.  
  4755. A:    In general, you cannot.  Ideally, you should provide a version
  4756.     of that other function which accepts a va_list pointer
  4757.     (analogous to vfprintf(); see question 15.5 above).  If the
  4758.     arguments must be passed directly as actual arguments, or if you
  4759.     do not have the option of rewriting the second function to
  4760.     accept a va_list (in other words, if the second, called function
  4761.     must accept a variable number of arguments, not a va_list), no
  4762.     portable solution is possible.  (The problem could perhaps be
  4763.     solved by resorting to machine-specific assembly language; see
  4764.     also question 15.13 below.)
  4765.  
  4766. 15.13:    How can I call a function with an argument list built up at run
  4767.     time?
  4768.  
  4769. A:    There is no guaranteed or portable way to do this.  If you're
  4770.     curious, ask this list's editor, who has a few wacky ideas you
  4771.     could try...
  4772.  
  4773.     Instead of an actual argument list, you might consider passing
  4774.     an array of generic (void *) pointers.  The called function can
  4775.     then step through the array, much like main() might step through
  4776.     argv.  (Obviously this works only if you have control over all
  4777.     the called functions.)
  4778.  
  4779.     (See also question 19.36.)
  4780.  
  4781.  
  4782. Section 16. Strange Problems
  4783.  
  4784. 16.1b:    I'm getting baffling syntax errors which make no sense at all,
  4785.     and it seems like large chunks of my program aren't being
  4786.     compiled.
  4787.  
  4788. A:    Check for unclosed comments or mismatched #if/#ifdef/#ifndef/
  4789.     #else/#endif directives; remember to check header files, too.
  4790.     (See also questions 2.18, 10.9, and 11.29.)
  4791.  
  4792. 16.1c:    Why isn't my procedure call working?  The compiler seems to skip
  4793.     right over it.
  4794.  
  4795. A:    Does the code look like this?
  4796.  
  4797.         myprocedure;
  4798.  
  4799.     C has only functions, and function calls always require
  4800.     parenthesized argument lists, even if empty.  Use
  4801.  
  4802.         myprocedure();
  4803.  
  4804. 16.3:    This program crashes before it even runs!  (When single-stepping
  4805.     with a debugger, it dies before the first statement in main().)
  4806.  
  4807. A:    You probably have one or more very large (kilobyte or more)
  4808.     local arrays.  Many systems have fixed-size stacks, and those
  4809.     which perform dynamic stack allocation automatically (e.g. Unix)
  4810.     can be confused when the stack tries to grow by a huge chunk all
  4811.     at once.  It is often better to declare large arrays with static
  4812.     duration (unless of course you need a fresh set with each
  4813.     recursive call, in which case you could dynamically allocate
  4814.     them with malloc(); see also question 1.31).
  4815.  
  4816.     (See also questions 11.12b, 16.4, 16.5, and 18.4.)
  4817.  
  4818. 16.4:    I have a program that seems to run correctly, but it crashes as
  4819.     it's exiting, *after* the last statement in main().  What could
  4820.     be causing this?
  4821.  
  4822. A:    Look for a misdeclared main() (see questions 2.18 and 10.9), or
  4823.     local buffers passed to setbuf() or setvbuf(), or problems in
  4824.     cleanup functions registered by atexit().  See also questions
  4825.     7.5a and 11.16.
  4826.  
  4827.     References: CT&P Sec. 5.3 pp. 72-3.
  4828.  
  4829. 16.5:    This program runs perfectly on one machine, but I get weird
  4830.     results on another.  Stranger still, adding or removing a
  4831.     debugging printout changes the symptoms...
  4832.  
  4833. A:    Lots of things could be going wrong; here are a few of the more
  4834.     common things to check:
  4835.  
  4836.         uninitialized local variables (see also question 7.1)
  4837.  
  4838.         integer overflow, especially on 16-bit machines,
  4839.         especially of an intermediate result when doing things
  4840.         like a * b / c (see also question 3.14)
  4841.  
  4842.         undefined evaluation order (see questions 3.1 through 3.4)
  4843.  
  4844.         omitted declaration of external functions, especially
  4845.         those which return something other than int, or have
  4846.         "narrow" or variable arguments (see questions 1.25, 11.3,
  4847.         14.2, and 15.1)
  4848.  
  4849.         dereferenced null pointers (see section 5)
  4850.  
  4851.         improper malloc/free use: assuming malloc'ed memory
  4852.         contains 0, assuming freed storage persists, freeing
  4853.         something twice, corrupting the malloc arena (see also
  4854.         questions 7.19 and 7.20)
  4855.  
  4856.         pointer problems in general (see also question 16.8)
  4857.  
  4858.         mismatch between printf() format and arguments, especially
  4859.         trying to print long ints using %d (see question 12.9)
  4860.  
  4861.         trying to allocate more memory than an unsigned int can
  4862.         count, especially on machines with limited memory (see
  4863.         also questions 7.16 and 19.23)
  4864.  
  4865.         array bounds problems, especially of small, temporary
  4866.         buffers, perhaps used for constructing strings with
  4867.         sprintf() (see also questions 7.1 and 12.21)
  4868.  
  4869.         invalid assumptions about the mapping of typedefs,
  4870.         especially size_t
  4871.  
  4872.         floating point problems (see questions 14.1 and 14.4)
  4873.  
  4874.         anything you thought was a clever exploitation of the way
  4875.         you believe code is generated for your specific system
  4876.  
  4877.     Proper use of function prototypes can catch several of these
  4878.     problems; lint would catch several more.  See also questions
  4879.     16.3, 16.4, and 18.4.
  4880.  
  4881. 16.6:    Why does this code:
  4882.  
  4883.         char *p = "hello, world!";
  4884.         p[0] = 'H';
  4885.  
  4886.     crash?
  4887.  
  4888. A:    String literals are not necessarily modifiable, except (in
  4889.     effect) when they are used as array initializers.  Try
  4890.  
  4891.         char a[] = "hello, world!";
  4892.  
  4893.     See also question 1.32.
  4894.  
  4895.     References: ISO Sec. 6.1.4; H&S Sec. 2.7.4 pp. 31-2.
  4896.  
  4897. 16.8:    What do "Segmentation violation" and "Bus error" mean?
  4898.  
  4899. A:    These generally mean that your program tried to access memory it
  4900.     shouldn't have, invariably as a result of stack corruption or
  4901.     improper pointer use.  Likely causes are overflow of local
  4902.     ("automatic," stack-allocated) arrays; inadvertent use of null
  4903.     pointers (see also questions 5.2 and 5.20) or uninitialized,
  4904.     misaligned, or otherwise improperly allocated pointers (see
  4905.     questions 7.1 and 7.2); corruption of the malloc arena (see
  4906.     question 7.19); and mismatched function arguments, especially
  4907.     involving pointers; two possibilities are scanf() (see question
  4908.     12.12) and fprintf() (make sure it receives its first FILE *
  4909.     argument).
  4910.  
  4911.     See also questions 16.3 and 16.4.
  4912.  
  4913.  
  4914. Section 17. Style
  4915.  
  4916. 17.1:    What's the best style for code layout in C?
  4917.  
  4918. A:    K&R, while providing the example most often copied, also supply
  4919.     a good excuse for disregarding it:
  4920.  
  4921.         The position of braces is less important,
  4922.         although people hold passionate beliefs.
  4923.         We have chosen one of several popular styles.
  4924.         Pick a style that suits you, then use it
  4925.         consistently.
  4926.  
  4927.     It is more important that the layout chosen be consistent (with
  4928.     itself, and with nearby or common code) than that it be
  4929.     "perfect."  If your coding environment (i.e. local custom or
  4930.     company policy) does not suggest a style, and you don't feel
  4931.     like inventing your own, just copy K&R.  (The tradeoffs between
  4932.     various indenting and brace placement options can be
  4933.     exhaustively and minutely examined, but don't warrant repetition
  4934.     here.  See also the Indian Hill Style Guide.)
  4935.  
  4936.     The elusive quality of "good style" involves much more than mere
  4937.     code layout details; don't spend time on formatting to the
  4938.     exclusion of more substantive code quality issues.
  4939.  
  4940.     See also question 10.6.
  4941.  
  4942.     References: K&R1 Sec. 1.2 p. 10; K&R2 Sec. 1.2 p. 10.
  4943.  
  4944. 17.3:    Here's a neat trick for checking whether two strings are equal:
  4945.  
  4946.         if(!strcmp(s1, s2))
  4947.  
  4948.     Is this good style?
  4949.  
  4950. A:    It is not particularly good style, although it is a popular
  4951.     idiom.  The test succeeds if the two strings are equal, but the
  4952.     use of ! ("not") suggests that it tests for inequality.
  4953.  
  4954.     Another option is to use a macro:
  4955.  
  4956.         #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
  4957.  
  4958.     See also question 17.10.
  4959.  
  4960. 17.4:    Why do some people write if(0 == x) instead of if(x == 0)?
  4961.  
  4962. A:    It's a trick to guard against the common error of writing
  4963.  
  4964.         if(x = 0)
  4965.  
  4966.     If you're in the habit of writing the constant before the ==,
  4967.     the compiler will complain if you accidentally type
  4968.  
  4969.         if(0 = x)
  4970.  
  4971.     Evidently it can be easier for some people to remember to
  4972.     reverse the test than to remember to type the doubled = sign.
  4973.     (Of course, the trick only helps when comparing to a constant.)
  4974.  
  4975.     References: H&S Sec. 7.6.5 pp. 209-10.
  4976.  
  4977. 17.5:    I came across some code that puts a (void) cast before each call
  4978.     to printf().  Why?
  4979.  
  4980. A:    printf() does return a value, though few programs bother to
  4981.     check the return values from each call.  Since some compilers
  4982.     (and lint) will warn about discarded return values, an explicit
  4983.     cast to (void) is a way of saying "Yes, I've decided to ignore
  4984.     the return value from this call, but please continue to warn me
  4985.     about other (perhaps inadvertently) ignored return values."
  4986.     It's also common to use void casts on calls to strcpy() and
  4987.     strcat(), since the return value is never surprising.
  4988.  
  4989.     References: K&R2 Sec. A6.7 p. 199; Rationale Sec. 3.3.4; H&S
  4990.     Sec. 6.2.9 p. 172, Sec. 7.13 pp. 229-30.
  4991.  
  4992. 17.8:    What is "Hungarian Notation"?  Is it worthwhile?
  4993.  
  4994. A:    Hungarian Notation is a naming convention, invented by Charles
  4995.     Simonyi, which encodes information about a variable's type (and
  4996.     perhaps its intended use) in its name.  It is well-loved in some
  4997.     circles and roundly castigated in others.  Its chief advantage
  4998.     is that it makes a variable's type or intended use obvious from
  4999.     its name; its chief disadvantage is that type information is not
  5000.     necessarily a worthwhile thing to carry around in the name of a
  5001.     variable.
  5002.  
  5003.     References: Simonyi and Heller, "The Hungarian Revolution" .
  5004.  
  5005. 17.9:    Where can I get the "Indian Hill Style Guide" and other coding
  5006.     standards?
  5007.  
  5008. A:    Various documents are available for anonymous ftp from:
  5009.  
  5010.         Site:            File or directory:
  5011.  
  5012.         ftp.cs.washington.edu    pub/cstyle.tar.Z
  5013.                     (the updated Indian Hill guide)
  5014.  
  5015.         ftp.cs.toronto.edu    doc/programming
  5016.                     (including Henry Spencer's
  5017.                     "10 Commandments for C Programmers")
  5018.  
  5019.         ftp.cs.umd.edu        pub/style-guide
  5020.  
  5021.     You may also be interested in the books _The Elements of
  5022.     Programming Style_, _Plum Hall Programming Guidelines_, and _C
  5023.     Style: Standards and Guidelines_; see the Bibliography.
  5024.  
  5025.     See also question 18.9.
  5026.  
  5027. 17.10:    Some people say that goto's are evil and that I should never use
  5028.     them.  Isn't that a bit extreme?
  5029.  
  5030. A:    Programming style, like writing style, is somewhat of an art and
  5031.     cannot be codified by inflexible rules, although discussions
  5032.     about style often seem to center exclusively around such rules.
  5033.  
  5034.     In the case of the goto statement, it has long been observed
  5035.     that unfettered use of goto's quickly leads to unmaintainable
  5036.     spaghetti code.  However, a simple, unthinking ban on the goto
  5037.     statement does not necessarily lead immediately to beautiful
  5038.     programming: an unstructured programmer is just as capable of
  5039.     constructing a Byzantine tangle without using any goto's
  5040.     (perhaps substituting oddly-nested loops and Boolean control
  5041.     variables, instead).
  5042.  
  5043.     Most observations or "rules" about programming style usually
  5044.     work better as guidelines than rules, and work much better if
  5045.     programmers understand what the guidelines are trying to
  5046.     accomplish.  Blindly avoiding certain constructs or following
  5047.     rules without understanding them can lead to just as many
  5048.     problems as the rules were supposed to avert.
  5049.  
  5050.     Furthermore, many opinions on programming style are just that:
  5051.     opinions.  It's usually futile to get dragged into "style wars,"
  5052.     because on certain issues (such as those referred to in
  5053.     questions 9.2, 5.3, 5.9, and 10.7), opponents can never seem to
  5054.     agree, or agree to disagree, or stop arguing.
  5055.  
  5056.  
  5057. Section 18. Tools and Resources
  5058.  
  5059. 18.1:    I need:                 A:    Look for programs (see also
  5060.                     question 18.16) named:
  5061.  
  5062.     a C cross-reference        cflow, cxref, calls, cscope,
  5063.     generator            xscope, or ixfw
  5064.  
  5065.     a C beautifier/pretty-        cb, indent, GNU indent, or
  5066.     printer                vgrind
  5067.  
  5068.     a revision control or        CVS, RCS, or SCCS
  5069.     configuration management
  5070.     tool
  5071.  
  5072.     a C source obfuscator        obfus, shroud, or opqcp
  5073.     (shrouder)
  5074.  
  5075.     a "make" dependency        makedepend, or try cc -M or
  5076.     generator            cpp -M
  5077.  
  5078.     tools to compute code        ccount, Metre, lcount, or csize,
  5079.     metrics                or see URL http://www.qucis.queensu.ca/
  5080.                     Software-Engineering/Cmetrics.html ;
  5081.                     there is also a package sold
  5082.                     by McCabe and Associates
  5083.  
  5084.     a C lines-of-source        this can be done very
  5085.     counter                crudely with the standard
  5086.                     Unix utility wc, and
  5087.                     somewhat better with
  5088.                     grep -c ";"
  5089.  
  5090.     a C declaration aid        check volume 14 of
  5091.     (cdecl)                comp.sources.unix (see
  5092.                     question 18.16) and K&R2
  5093.  
  5094.     a prototype generator        see question 11.31
  5095.  
  5096.     a tool to track down
  5097.     malloc problems            see question 18.2
  5098.  
  5099.     a "selective" C
  5100.     preprocessor            see question 10.18
  5101.  
  5102.     language translation        see questions 11.31 and
  5103.     tools                 20.26
  5104.  
  5105.     C verifiers (lint)        see question 18.7
  5106.  
  5107.     a C compiler!            see question 18.3
  5108.  
  5109.     (This list of tools is by no means complete; if you know of
  5110.     tools not mentioned, you're welcome to contact this list's
  5111.     maintainer.)
  5112.  
  5113.     Other lists of tools, and discussion about them, can be found in
  5114.     the Usenet newsgroups comp.compilers and comp.software-eng.
  5115.  
  5116.     See also questions 18.3 and 18.16.
  5117.  
  5118. 18.2:    How can I track down these pesky malloc problems?
  5119.  
  5120. A:    A number of debugging packages exist to help track down malloc
  5121.     problems; one popular one is Conor P. Cahill's "dbmalloc",
  5122.     posted to comp.sources.misc in 1992, volume 32.  Others are
  5123.     "leak", available in volume 27 of the comp.sources.unix
  5124.     archives; JMalloc.c and JMalloc.h in the "Snippets" collection;
  5125.     and MEMDEBUG from ftp.crpht.lu in pub/sources/memdebug .  See
  5126.     also question 18.16.
  5127.  
  5128.     A number of commercial debugging tools exist, and can be
  5129.     invaluable in tracking down malloc-related and other stubborn
  5130.     problems:
  5131.  
  5132.         Bounds-Checker for DOS, from Nu-Mega Technologies,
  5133.         P.O. Box 7780, Nashua, NH 03060-7780, USA, 603-889-2386.
  5134.  
  5135.         CodeCenter (formerly Saber-C) from Centerline Software,
  5136.         10 Fawcett Street, Cambridge, MA 02138, USA, 617-498-3000.
  5137.  
  5138.         Insight, from ParaSoft Corporation, 2500 E. Foothill
  5139.         Blvd., Pasadena, CA 91107, USA, 818-792-9941,
  5140.         insight@parasoft.com .
  5141.  
  5142.         Purify, from Pure Software, 1309 S. Mary Ave., Sunnyvale,
  5143.         CA 94087, USA, 800-224-7873, http://www.pure.com ,
  5144.         info-home@pure.com .
  5145.         (I believe Pure was recently acquired by Rational.)
  5146.  
  5147.         Final Exam Memory Advisor, from PLATINUM Technology
  5148.         (formerly Sentinel from AIB Software), 1815 South Meyers
  5149.         Rd., Oakbrook Terrace, IL 60181, USA, 630-620-5000,
  5150.         800-442-6861, info@platinum.com, www.platinum.com .
  5151.  
  5152.         ZeroFault, from The Kernel Group, 1250 Capital of Texas
  5153.         Highway South, Building Three, Suite 601, Austin,
  5154.         TX 78746, 512-433-3333, http://www.tkg.com, zf@tkg.com .
  5155.  
  5156. 18.3:    What's a free or cheap C compiler I can use?
  5157.  
  5158. A:    A popular and high-quality free C compiler is the FSF's GNU C
  5159.     compiler, or gcc.  It is available by anonymous ftp from
  5160.     prep.ai.mit.edu in directory pub/gnu, or at several other FSF
  5161.     archive sites.  An MS-DOS port, djgpp, is also available;
  5162.     see the djgpp home page at http://www.delorie.com/djgpp/ .
  5163.  
  5164.     There is a shareware compiler called PCC, available as
  5165.     PCC12C.ZIP .
  5166.  
  5167.     A very inexpensive MS-DOS compiler is Power C from Mix Software,
  5168.     1132 Commerce Drive, Richardson, TX 75801, USA, 214-783-6001.
  5169.  
  5170.     Another recently-developed compiler is lcc, available for
  5171.     anonymous ftp from ftp.cs.princeton.edu in pub/lcc/.
  5172.  
  5173.     A shareware MS-DOS C compiler is available from
  5174.     ftp.hitech.com.au/hitech/pacific.  Registration is optional for
  5175.     non-commercial use.
  5176.  
  5177.     There are currently no viable shareware compilers for the
  5178.     Macintosh.
  5179.  
  5180.     Archives associated with comp.compilers contain a great deal of
  5181.     information about available compilers, interpreters, grammars,
  5182.     etc. (for many languages).  The comp.compilers archives
  5183.     (including an FAQ list), maintained by the moderator, John R.
  5184.     Levine, are at iecc.com .  A list of available compilers and
  5185.     related resources, maintained by Mark Hopkins, Steven Robenalt,
  5186.     and David Muir Sharnoff, is at ftp.idiom.com in pub/compilers-
  5187.     list/.  (See also the comp.compilers directory in the
  5188.     news.answers archives at rtfm.mit.edu and ftp.uu.net; see
  5189.     question 20.40.)
  5190.  
  5191.     See also question 18.16.
  5192.  
  5193. 18.4:    I just typed in this program, and it's acting strangely.  Can
  5194.     you see anything wrong with it?
  5195.  
  5196. A:    See if you can run lint first (perhaps with the -a, -c, -h, -p
  5197.     or other options).  Many C compilers are really only half-
  5198.     compilers, electing not to diagnose numerous source code
  5199.     difficulties which would not actively preclude code generation.
  5200.  
  5201.     See also questions 16.5, 16.8, and 18.7.
  5202.  
  5203.     References: Ian Darwin, _Checking C Programs with lint_ .
  5204.  
  5205. 18.5:    How can I shut off the "warning: possible pointer alignment
  5206.     problem" message which lint gives me for each call to malloc()?
  5207.  
  5208. A:    The problem is that traditional versions of lint do not know,
  5209.     and cannot be told, that malloc() "returns a pointer to space
  5210.     suitably aligned for storage of any type of object."  It is
  5211.     possible to provide a pseudoimplementation of malloc(), using a
  5212.     #define inside of #ifdef lint, which effectively shuts this
  5213.     warning off, but a simpleminded definition will also suppress
  5214.     meaningful messages about truly incorrect invocations.  It may
  5215.     be easier simply to ignore the message, perhaps in an automated
  5216.     way with grep -v.  (But don't get in the habit of ignoring too
  5217.     many lint messages, otherwise one day you'll overlook a
  5218.     significant one.)
  5219.  
  5220. 18.7:    Where can I get an ANSI-compatible lint?
  5221.  
  5222. A:    Products called PC-Lint and FlexeLint (in "shrouded source
  5223.     form," for compilation on 'most any system) are available from
  5224.  
  5225.         Gimpel Software
  5226.         3207 Hogarth Lane
  5227.         Collegeville, PA  19426  USA
  5228.         (+1) 610 584 4261
  5229.         gimpel@netaxs.com
  5230.  
  5231.     The Unix System V release 4 lint is ANSI-compatible, and is
  5232.     available separately (bundled with other C tools) from UNIX
  5233.     Support Labs or from System V resellers.
  5234.  
  5235.     Another ANSI-compatible lint (which can also perform higher-
  5236.     level formal verification) is LCLint, available via anonymous
  5237.     ftp from larch.lcs.mit.edu in pub/Larch/lclint/.
  5238.  
  5239.     In the absence of lint, many modern compilers do attempt to
  5240.     diagnose almost as many problems as lint does.  (Many netters
  5241.     recommend gcc -Wall -pedantic .)
  5242.  
  5243. 18.8:    Don't ANSI function prototypes render lint obsolete?
  5244.  
  5245. A:    No.  First of all, prototypes work only if they are present and
  5246.     correct; an inadvertently incorrect prototype is worse than
  5247.     useless.  Secondly, lint checks consistency across multiple
  5248.     source files, and checks data declarations as well as functions.
  5249.     Finally, an independent program like lint will probably always
  5250.     be more scrupulous at enforcing compatible, portable coding
  5251.     practices than will any particular, implementation-specific,
  5252.     feature- and extension-laden compiler.
  5253.  
  5254.     If you do want to use function prototypes instead of lint for
  5255.     cross-file consistency checking, make sure that you set the
  5256.     prototypes up correctly in header files.  See questions 1.7 and
  5257.     10.6.
  5258.  
  5259. 18.9:    Are there any C tutorials or other resources on the net?
  5260.  
  5261. A:    There are several of them:
  5262.  
  5263.     Tom Torfs has a nice tutorial at
  5264.     http://members.xoom.com/tomtorfs/cintro.html .
  5265.  
  5266.     "Notes for C programmers," by Christopher Sawtell, are
  5267.     available from svr-ftp.eng.cam.ac.uk in misc/sawtell_C.shar and
  5268.     garbo.uwasa.fi in /pc/c-lang/c-lesson.zip .
  5269.  
  5270.     Tim Love's "C for Programmers" is available by ftp from svr-
  5271.     ftp.eng.cam.ac.uk in the misc directory.  An html version is at
  5272.     http://www-h.eng.cam.ac.uk/help/tpl/languages/C/teaching_C/
  5273.     teaching_C.html .
  5274.  
  5275.     The Coronado Enterprises C tutorials are available on Simtel
  5276.     mirrors in pub/msdos/c or on the web at http://www.swcp.com/~dodrill .
  5277.  
  5278.     Rick Rowe has a tutorial which is available from ftp.netcom.com
  5279.     as pub/rowe/tutorde.zip or ftp.wustl.edu as
  5280.     pub/MSDOS_UPLOADS/programming/c_language/ctutorde.zip .
  5281.  
  5282.     There is evidently a web-based course at
  5283.     http://www.strath.ac.uk/CC/Courses/CCourse/CCourse.html .
  5284.  
  5285.     Martin Brown has C course material on the web at
  5286.     http://www-isis.ecs.soton.ac.uk/computing/c/Welcome.html .
  5287.  
  5288.     On some Unix machines you can try typing "learn c" at the shell
  5289.     prompt (but the lessons may be quite dated).
  5290.  
  5291.     Finally, the author of this FAQ list teaches a C class
  5292.     and has placed its notes on the web; they are at
  5293.     http://www.eskimo.com/~scs/cclass/cclass.html .
  5294.  
  5295.     [Disclaimer: I have not reviewed many of these tutorials, and
  5296.     I gather that they tend to contain errors.  With the exception
  5297.     of the one with my name on it, I can't vouch for any of them.
  5298.     Also, this sort of information rapidly becomes out-of-date;
  5299.     these addresses may not work by the time you read this and
  5300.     try them.]
  5301.  
  5302.     Several of these tutorials, plus a great deal of other
  5303.     information about C, are accessible via the web at
  5304.     http://www.lysator.liu.se/c/index.html .
  5305.  
  5306.     Vinit Carpenter maintains a list of resources for learning C and
  5307.     C++; it is posted to comp.lang.c and comp.lang.c++, and archived
  5308.     where this FAQ list is (see question 20.40), or on the web at
  5309.     http://www.cyberdiem.com/vin/learn.html .
  5310.  
  5311.     See also questions 18.10 and 18.15c.
  5312.  
  5313. 18.10:    What's a good book for learning C?
  5314.  
  5315. A:    There are far too many books on C to list here; it's impossible
  5316.     to rate them all.  Many people believe that the best one was
  5317.     also the first: _The C Programming Language_, by Kernighan and
  5318.     Ritchie ("K&R," now in its second edition).  Opinions vary on
  5319.     K&R's suitability as an initial programming text: many of us did
  5320.     learn C from it, and learned it well; some, however, feel that
  5321.     it is a bit too clinical as a first tutorial for those without
  5322.     much programming background.  Several sets of annotations and
  5323.     errata are available on the net, see e.g.
  5324.     http://www.csd.uwo.ca/~jamie/.Refs/.Footnotes/C-annotes.html,
  5325.     http://www.eskimo.com/~scs/cclass/cclass.html, and
  5326.     http://www.lysator.liu.se/c/c-errata.html#main .
  5327.  
  5328.     Many comp.lang.c regulars recommend _C: A Modern Approach_,
  5329.     by K.N. King.
  5330.  
  5331.     An excellent reference manual is _C: A Reference Manual_, by
  5332.     Samuel P. Harbison and Guy L. Steele, now in its fourth edition.
  5333.  
  5334.     Though not suitable for learning C from scratch, this FAQ list
  5335.     has been published in book form; see the Bibliography.
  5336.  
  5337.     Mitch Wright maintains an annotated bibliography of C and Unix
  5338.     books; it is available for anonymous ftp from ftp.rahul.net in
  5339.     directory pub/mitch/YABL/.
  5340.  
  5341.     Scott McMahon has a nice set of reviews at
  5342.     http://www.skwc.com/essent/cyberreviews.html .
  5343.  
  5344.     The Association of C and C++ Users (ACCU) maintains a
  5345.     comprehensive set of bibliographic reviews of C/C++ titles, at
  5346.     http://bach.cis.temple.edu/accu/bookcase or
  5347.     http://www.accu.org/accu .
  5348.  
  5349.     This FAQ list's editor has a large collection of assorted
  5350.     old recommendations which various people have posted; it
  5351.     is available upon request.  See also question 18.9 above.
  5352.  
  5353. 18.13:    Where can I find the sources of the standard C libraries?
  5354.  
  5355. A:    One source (though not public domain) is _The Standard C
  5356.     Library_, by P.J. Plauger (see the Bibliography).
  5357.     Implementations of all or part of the C library have been
  5358.     written and are readily available as part of the NetBSD and GNU
  5359.     (also Linux) projects.  See also questions 18.15c and 18.16.
  5360.  
  5361. 18.13b:    Is there an on-line C reference manual?
  5362.  
  5363. A:    Two possibilities are
  5364.     http://www.cs.man.ac.uk/standard_c/_index.html and
  5365.     http://www.dinkumware.com/htm_cl/index.html .
  5366.  
  5367. 18.13c:    Where can I get a copy of the ANSI/ISO C Standard?
  5368.  
  5369. A:    See question 11.2.
  5370.  
  5371. 18.14:    I need code to parse and evaluate expressions.
  5372.  
  5373. A:    Two available packages are "defunc," posted to comp.sources.misc
  5374.     in December, 1993 (V41 i32,33), to alt.sources in January, 1994,
  5375.     and available from sunsite.unc.edu in
  5376.     pub/packages/development/libraries/defunc-1.3.tar.Z, and
  5377.     "parse," at lamont.ldgo.columbia.edu.  Other options include the
  5378.     S-Lang interpreter, available via anonymous ftp from
  5379.     amy.tch.harvard.edu in pub/slang, and the shareware Cmm ("C-
  5380.     minus-minus" or "C minus the hard stuff").  See also questions
  5381.     18.16 and 20.6.
  5382.  
  5383.     There is also some parsing/evaluation code in _Software
  5384.     Solutions in C_ (chapter 12, pp. 235-55).
  5385.  
  5386. 18.15:    Where can I get a BNF or YACC grammar for C?
  5387.  
  5388. A:    The definitive grammar is of course the one in the ANSI
  5389.     standard; see question 11.2.  Another grammar (along with
  5390.     one for C++) by Jim Roskind is in pub/c++grammar1.1.tar.Z
  5391.     at ics.uci.edu (or perhaps ftp.ics.uci.edu, or perhaps
  5392.     OLD/pub/c++grammar1.1.tar.Z), or at ftp.eskimo.com in
  5393.     u/s/scs/roskind_grammar.Z .  A fleshed-out, working instance
  5394.     of the ANSI grammar (due to Jeff Lee) is on ftp.uu.net
  5395.     (see question 18.16) in usenet/net.sources/ansi.c.grammar.Z
  5396.     (including a companion lexer).  The FSF's GNU C compiler
  5397.     contains a grammar, as does the appendix to K&R2.
  5398.  
  5399.     The comp.compilers archives contain more information about
  5400.     grammars; see question 18.3.
  5401.  
  5402.     References: K&R1 Sec. A18 pp. 214-219; K&R2 Sec. A13 pp. 234-
  5403.     239; ISO Sec. B.2; H&S pp. 423-435 Appendix B.
  5404.  
  5405. 18.15b:    Does anyone have a C compiler test suite I can use?
  5406.  
  5407. A:    Plum Hall (formerly in Cardiff, NJ; now in Hawaii) sells one;
  5408.     other packages are Ronald Guilmette's RoadTest(tm) Compiler Test
  5409.     Suites (ftp to netcom.com, pub/rfg/roadtest/announce.txt for
  5410.     information) and Nullstone's Automated Compiler Performance
  5411.     Analysis Tool (see http://www.nullstone.com).  The FSF's GNU C
  5412.     (gcc) distribution includes a c-torture-test which checks a
  5413.     number of common problems with compilers.  Kahan's paranoia
  5414.     test, found in netlib/paranoia on netlib.att.com, strenuously
  5415.     tests a C implementation's floating point capabilities.
  5416.  
  5417. 18.15c:    Where are some collections of useful code fragments and
  5418.     examples?
  5419.  
  5420. A:    Bob Stout's popular "SNIPPETS" collection is available from
  5421.     ftp.brokersys.com in directory pub/snippets or on the web at
  5422.     http://www.brokersys.com/snippets/ .
  5423.  
  5424.     Lars Wirzenius's "publib" library is available from ftp.funet.fi
  5425.     in directory pub/languages/C/Publib/.
  5426.  
  5427.     See also questions 14.12, 18.9, 18.13, and 18.16.
  5428.  
  5429. 18.15d:    I need code for performing multiple precision arithmetic.
  5430.  
  5431. A:    Some popular packages are the "quad" functions within the BSD
  5432.     Unix libc sources (ftp.uu.net, /systems/unix/bsd-sources/..../
  5433.     /src/lib/libc/quad/*), the GNU MP library, the MIRACL package
  5434.     (see http://indigo.ie/~mscott/ ), and the old Unix libmp.a.
  5435.     See also questions 14.12 and 18.16.
  5436.  
  5437.     References: Schumacher, ed., _Software Solutions in C_ Sec. 17
  5438.     pp. 343-454.
  5439.  
  5440. 18.16:    Where and how can I get copies of all these freely distributable
  5441.     programs?
  5442.  
  5443. A:    As the number of available programs, the number of publicly
  5444.     accessible archive sites, and the number of people trying to
  5445.     access them all grow, this question becomes both easier and more
  5446.     difficult to answer.
  5447.  
  5448.     There are a number of large, public-spirited archive sites out
  5449.     there, such as ftp.uu.net, archive.umich.edu, oak.oakland.edu,
  5450.     sumex-aim.stanford.edu, and wuarchive.wustl.edu, which have huge
  5451.     amounts of software and other information all freely available.
  5452.     For the FSF's GNU project, the central distribution site is
  5453.     prep.ai.mit.edu .  These well-known sites tend to be extremely
  5454.     busy and hard to reach, but there are also numerous "mirror"
  5455.     sites which try to spread the load around.
  5456.  
  5457.     On the connected Internet, the traditional way to retrieve files
  5458.     from an archive site is with anonymous ftp.  For those without
  5459.     ftp access, there are also several ftp-by-mail servers in
  5460.     operation.  More and more, the world-wide web (WWW) is being
  5461.     used to announce, index, and even transfer large data files.
  5462.     There are probably yet newer access methods, too.
  5463.  
  5464.     Those are some of the easy parts of the question to answer.  The
  5465.     hard part is in the details -- this article cannot begin to
  5466.     track or list all of the available archive sites or all of the
  5467.     various ways of accessing them.  If you have access to the net
  5468.     at all, you probably have access to more up-to-date information
  5469.     about active sites and useful access methods than this FAQ list
  5470.     does.
  5471.  
  5472.     The other easy-and-hard aspect of the question, of course, is
  5473.     simply *finding* which site has what you're looking for.  There
  5474.     is a tremendous amount of work going on in this area, and there
  5475.     are probably new indexing services springing up every day.  One
  5476.     of the first was "archie", and of course there are a number of
  5477.     high-profile commercial net indexing and searching services such
  5478.     as Alta Vista, Excite, and Yahoo.
  5479.  
  5480.     If you have access to Usenet, see the regular postings in the
  5481.     comp.sources.unix and comp.sources.misc newsgroups, which
  5482.     describe the archiving policies for those groups and how to
  5483.     access their archives, two of which are
  5484.     ftp://gatekeeper.dec.com/pub/usenet/comp.sources.unix/ and
  5485.     ftp://ftp.uu.net/usenet/comp.sources.unix/.  The comp.archives
  5486.     newsgroup contains numerous announcements of anonymous ftp
  5487.     availability of various items.  Finally, the newsgroup
  5488.     comp.sources.wanted is generally a more appropriate place to
  5489.     post queries for source availability, but check *its* FAQ list,
  5490.     "How to find sources," before posting there.
  5491.  
  5492.     See also questions 14.12, 18.13, and 18.15c.
  5493.  
  5494.  
  5495. Section 19. System Dependencies
  5496.  
  5497. 19.1:    How can I read a single character from the keyboard without
  5498.     waiting for the RETURN key?  How can I stop characters from
  5499.     being echoed on the screen as they're typed?
  5500.  
  5501. A:    Alas, there is no standard or portable way to do these things in
  5502.     C.  Concepts such as screens and keyboards are not even
  5503.     mentioned in the Standard, which deals only with simple I/O
  5504.     "streams" of characters.
  5505.  
  5506.     At some level, interactive keyboard input is usually collected
  5507.     and presented to the requesting program a line at a time.  This
  5508.     gives the operating system a chance to support input line
  5509.     editing (backspace/delete/rubout, etc.) in a consistent way,
  5510.     without requiring that it be built into every program.  Only
  5511.     when the user is satisfied and presses the RETURN key (or
  5512.     equivalent) is the line made available to the calling program.
  5513.     Even if the calling program appears to be reading input a
  5514.     character at a time (with getchar() or the like), the first call
  5515.     blocks until the user has typed an entire line, at which point
  5516.     potentially many characters become available and many character
  5517.     requests (e.g. getchar() calls) are satisfied in quick
  5518.     succession.
  5519.  
  5520.     When a program wants to read each character immediately as it
  5521.     arrives, its course of action will depend on where in the input
  5522.     stream the line collection is happening and how it can be
  5523.     disabled.  Under some systems (e.g. MS-DOS, VMS in some modes),
  5524.     a program can use a different or modified set of OS-level input
  5525.     calls to bypass line-at-a-time input processing.  Under other
  5526.     systems (e.g. Unix, VMS in other modes), the part of the
  5527.     operating system responsible for serial input (often called the
  5528.     "terminal driver") must be placed in a mode which turns off line-
  5529.     at-a-time processing, after which all calls to the usual input
  5530.     routines (e.g. read(), getchar(), etc.) will return characters
  5531.     immediately.  Finally, a few systems (particularly older, batch-
  5532.     oriented mainframes) perform input processing in peripheral
  5533.     processors which cannot be told to do anything other than line-
  5534.     at-a-time input.
  5535.  
  5536.     Therefore, when you need to do character-at-a-time input (or
  5537.     disable keyboard echo, which is an analogous problem), you will
  5538.     have to use a technique specific to the system you're using,
  5539.     assuming it provides one.  Since comp.lang.c is oriented towards
  5540.     those topics that the C language has defined support for, you
  5541.     will usually get better answers to other questions by referring
  5542.     to a system-specific newsgroup such as comp.unix.questions or
  5543.     comp.os.msdos.programmer, and to the FAQ lists for these groups.
  5544.     Note that the answers are often not unique even across different
  5545.     variants of a system; bear in mind when answering system-
  5546.     specific questions that the answer that applies to your system
  5547.     may not apply to everyone else's.
  5548.  
  5549.     However, since these questions are frequently asked here, here
  5550.     are brief answers for some common situations.
  5551.  
  5552.     Some versions of curses have functions called cbreak(),
  5553.     noecho(), and getch() which do what you want.  If you're
  5554.     specifically trying to read a short password without echo, you
  5555.     might try getpass().  Under Unix, you can use ioctl() to play
  5556.     with the terminal driver modes (CBREAK or RAW under "classic"
  5557.     versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or
  5558.     POSIX systems; ECHO under all versions), or in a pinch, system()
  5559.     and the stty command.  (For more information, see <sgtty.h> and
  5560.     tty(4) under classic versions, <termio.h> and termio(4) under
  5561.     System V, or <termios.h> and termios(4) under POSIX.)  Under
  5562.     MS-DOS, use getch() or getche(), or the corresponding BIOS
  5563.     interrupts.  Under VMS, try the Screen Management (SMG$)
  5564.     routines, or curses, or issue low-level $QIO's with the
  5565.     IO$_READVBLK function code (and perhaps IO$M_NOECHO, and others)
  5566.     to ask for one character at a time.  (It's also possible to set
  5567.     character-at-a-time or "pass through" modes in the VMS terminal
  5568.     driver.)  Under other operating systems, you're on your own.
  5569.  
  5570.     (As an aside, note that simply using setbuf() or setvbuf() to
  5571.     set stdin to unbuffered will *not* generally serve to allow
  5572.     character-at-a-time input.)
  5573.  
  5574.     If you're trying to write a portable program, a good approach is
  5575.     to define your own suite of three functions to (1) set the
  5576.     terminal driver or input system into character-at-a-time mode
  5577.     (if necessary), (2) get characters, and (3) return the terminal
  5578.     driver to its initial state when the program is finished.
  5579.     (Ideally, such a set of functions might be part of the C
  5580.     Standard, some day.)  The extended versions of this FAQ list
  5581.     (see question 20.40) contain examples of such functions for
  5582.     several popular systems.
  5583.  
  5584.     See also question 19.2.
  5585.  
  5586.     References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1; POSIX
  5587.     Sec. 7.
  5588.  
  5589. 19.2:    How can I find out if there are characters available for reading
  5590.     (and if so, how many)?  Alternatively, how can I do a read that
  5591.     will not block if there are no characters available?
  5592.  
  5593. A:    These, too, are entirely operating-system-specific.  Some
  5594.     versions of curses have a nodelay() function.  Depending on your
  5595.     system, you may also be able to use "nonblocking I/O", or a
  5596.     system call named "select" or "poll", or the FIONREAD ioctl, or
  5597.     c_cc[VTIME], or kbhit(), or rdchk(), or the O_NDELAY option to
  5598.     open() or fcntl().  See also question 19.1.
  5599.  
  5600. 19.3:    How can I display a percentage-done indication that updates
  5601.     itself in place, or show one of those "twirling baton" progress
  5602.     indicators?
  5603.  
  5604. A:    These simple things, at least, you can do fairly portably.
  5605.     Printing the character '\r' will usually give you a carriage
  5606.     return without a line feed, so that you can overwrite the
  5607.     current line.  The character '\b' is a backspace, and will
  5608.     usually move the cursor one position to the left.
  5609.  
  5610.     References: ISO Sec. 5.2.2.
  5611.  
  5612. 19.4:    How can I clear the screen?
  5613.     How can I print text in color?
  5614.     How can I move the cursor to a specific x, y position?
  5615.  
  5616. A:    Such things depend on the terminal type (or display) you're
  5617.     using.  You will have to use a library such as termcap,
  5618.     terminfo, or curses, or some system-specific routines, to
  5619.     perform these operations.  On MS-DOS systems, two functions
  5620.     to look for are clrscr() and gotoxy().
  5621.  
  5622.     For clearing the screen, a halfway portable solution is to print
  5623.     a form-feed character ('\f'), which will cause some displays to
  5624.     clear.  Even more portable (albeit even more gunky) might be to
  5625.     print enough newlines to scroll everything away.  As a last
  5626.     resort, you could use system() (see question 19.27) to invoke
  5627.     an operating system clear-screen command.
  5628.  
  5629.     References: PCS Sec. 5.1.4 pp. 54-60, Sec. 5.1.5 pp. 60-62.
  5630.  
  5631. 19.5:    How do I read the arrow keys?  What about function keys?
  5632.  
  5633. A:    Terminfo, some versions of termcap, and some versions of curses
  5634.     have support for these non-ASCII keys.  Typically, a special key
  5635.     sends a multicharacter sequence (usually beginning with ESC,
  5636.     '\033'); parsing these can be tricky.  (curses will do the
  5637.     parsing for you, if you call keypad() first.)
  5638.  
  5639.     Under MS-DOS, if you receive a character with value 0 (*not*
  5640.     '0'!) while reading the keyboard, it's a flag indicating that
  5641.     the next character read will be a code indicating a special key.
  5642.     See any DOS programming guide for lists of keyboard scan codes.
  5643.     (Very briefly: the up, left, right, and down arrow keys are 72,
  5644.     75, 77, and 80, and the function keys are 59 through 68.)
  5645.  
  5646.     References: PCS Sec. 5.1.4 pp. 56-7.
  5647.  
  5648. 19.6:    How do I read the mouse?
  5649.  
  5650. A:    Consult your system documentation, or ask on an appropriate
  5651.     system-specific newsgroup (but check its FAQ list first).  Mouse
  5652.     handling is completely different under the X window system, MS-
  5653.     DOS, the Macintosh, and probably every other system.
  5654.  
  5655.     References: PCS Sec. 5.5 pp. 78-80.
  5656.  
  5657. 19.7:    How can I do serial ("comm") port I/O?
  5658.  
  5659. A:    It's system-dependent.  Under Unix, you typically open, read,
  5660.     and write a device file in /dev, and use the facilities of the
  5661.     terminal driver to adjust its characteristics.  (See also
  5662.     questions 19.1 and 19.2.)  Under MS-DOS, you can use the
  5663.     predefined stream stdaux, or a special file like COM1, or some
  5664.     primitive BIOS interrupts, or (if you require decent
  5665.     performance) any number of interrupt-driven serial I/O packages.
  5666.     Several netters recommend the book _C Programmer's Guide to
  5667.     Serial Communications_, by Joe Campbell.
  5668.  
  5669. 19.8:    How can I direct output to the printer?
  5670.  
  5671. A:    Under Unix, either use popen() (see question 19.30) to write to
  5672.     the lp or lpr program, or perhaps open a special file like
  5673.     /dev/lp.  Under MS-DOS, write to the (nonstandard) predefined
  5674.     stdio stream stdprn, or open the special files PRN or LPT1.
  5675.  
  5676.     References: PCS Sec. 5.3 pp. 72-74.
  5677.  
  5678. 19.9:    How do I send escape sequences to control a terminal or other
  5679.     device?
  5680.  
  5681. A:    If you can figure out how to send characters to the device at
  5682.     all (see question 19.8 above), it's easy enough to send escape
  5683.     sequences.  In ASCII, the ESC code is 033 (27 decimal), so code
  5684.     like
  5685.  
  5686.         fprintf(ofd, "\033[J");
  5687.  
  5688.     sends the sequence ESC [ J .
  5689.  
  5690. 19.10:    How can I do graphics?
  5691.  
  5692. A:    Once upon a time, Unix had a fairly nice little set of device-
  5693.     independent plot functions described in plot(3) and plot(5).
  5694.     The GNU libplot package maintains the same spirit and supports
  5695.     many modern plot devices;
  5696.     see http://www.gnu.org/software/plotutils/plotutils.html .
  5697.  
  5698.     If you're programming for MS-DOS, you'll probably want to use
  5699.     libraries conforming to the VESA or BGI standards.
  5700.  
  5701.     If you're trying to talk to a particular plotter, making it draw
  5702.     is usually a matter of sending it the appropriate escape
  5703.     sequences; see also question 19.9.  The vendor may supply a C-
  5704.     callable library, or you may be able to find one on the net.
  5705.  
  5706.     If you're programming for a particular window system (Macintosh,
  5707.     X windows, Microsoft Windows), you will use its facilities; see
  5708.     the relevant documentation or newsgroup or FAQ list.
  5709.  
  5710.     References: PCS Sec. 5.4 pp. 75-77.
  5711.  
  5712. 19.11:    How can I check whether a file exists?  I want to warn the user
  5713.     if a requested input file is missing.
  5714.  
  5715. A:    It's surprisingly difficult to make this determination reliably
  5716.     and portably.  Any test you make can be invalidated if the file
  5717.     is created or deleted (i.e. by some other process) between the
  5718.     time you make the test and the time you try to open the file.
  5719.  
  5720.     Three possible test functions are stat(), access(), and fopen().
  5721.     (To make an approximate test using fopen(), just open for
  5722.     reading and close immediately, although failure does not
  5723.     necessarily indicate nonexistence.)  Of these, only fopen() is
  5724.     widely portable, and access(), where it exists, must be used
  5725.     carefully if the program uses the Unix set-UID feature.
  5726.  
  5727.     Rather than trying to predict in advance whether an operation
  5728.     such as opening a file will succeed, it's often better to try
  5729.     it, check the return value, and complain if it fails.
  5730.     (Obviously, this approach won't work if you're trying to avoid
  5731.     overwriting an existing file, unless you've got something like
  5732.     the O_EXCL file opening option available, which does just what
  5733.     you want in this case.)
  5734.  
  5735.     References: PCS Sec. 12 pp. 189,213; POSIX Sec. 5.3.1,
  5736.     Sec. 5.6.2, Sec. 5.6.3.
  5737.  
  5738. 19.12:    How can I find out the size of a file, prior to reading it in?
  5739.  
  5740. A:    If the "size of a file" is the number of characters you'll be
  5741.     able to read from it in C, it is difficult or impossible to
  5742.     determine this number exactly.
  5743.  
  5744.     Under Unix, the stat() call will give you an exact answer.
  5745.     Several other systems supply a Unix-like stat() which will give
  5746.     an approximate answer.  You can fseek() to the end and then use
  5747.     ftell(), or maybe try fstat(), but these tend to have the same
  5748.     sorts of problems: fstat() is not portable, and generally tells
  5749.     you the same thing stat() tells you; ftell() is not guaranteed
  5750.     to return a byte count except for binary files.  Some systems
  5751.     provide functions called filesize() or filelength(), but these
  5752.     are obviously not portable, either.
  5753.  
  5754.     Are you sure you have to determine the file's size in advance?
  5755.     Since the most accurate way of determining the size of a file as
  5756.     a C program will see it is to open the file and read it, perhaps
  5757.     you can rearrange the code to learn the size as it reads.
  5758.  
  5759.     References: ISO Sec. 7.9.9.4; H&S Sec. 15.5.1; PCS Sec. 12 p.
  5760.     213; POSIX Sec. 5.6.2.
  5761.  
  5762. 19.12b:    How can I find the modification date and time of a file?
  5763.  
  5764. A:    The Unix and POSIX function is stat(), which several other
  5765.     systems supply as well.  (See also question 19.12.)
  5766.  
  5767. 19.13:    How can a file be shortened in-place without completely clearing
  5768.     or rewriting it?
  5769.  
  5770. A:    BSD systems provide ftruncate(), several others supply chsize(),
  5771.     and a few may provide a (possibly undocumented) fcntl option
  5772.     F_FREESP.  Under MS-DOS, you can sometimes use write(fd, "", 0).
  5773.     However, there is no portable solution, nor a way to delete
  5774.     blocks at the beginning.  See also question 19.14.
  5775.  
  5776. 19.14:    How can I insert or delete a line (or record) in the middle of a
  5777.     file?
  5778.  
  5779. A:    Short of rewriting the file, you probably can't.  The usual
  5780.     solution is simply to rewrite the file.  (Instead of deleting
  5781.     records, you might consider simply marking them as deleted, to
  5782.     avoid rewriting.)  Another possibility, of course, is to use a
  5783.     database instead of a flat file.  See also questions 12.30 and
  5784.     19.13.
  5785.  
  5786. 19.15:    How can I recover the file name given an open stream or file
  5787.     descriptor?
  5788.  
  5789. A:    This problem is, in general, insoluble.  Under Unix, for
  5790.     instance, a scan of the entire disk (perhaps involving special
  5791.     permissions) would theoretically be required, and would fail if
  5792.     the descriptor were connected to a pipe or referred to a deleted
  5793.     file (and could give a misleading answer for a file with
  5794.     multiple links).  It is best to remember the names of files
  5795.     yourself as you open them (perhaps with a wrapper function
  5796.     around fopen()).
  5797.  
  5798. 19.16:    How can I delete a file?
  5799.  
  5800. A:    The Standard C Library function is remove().  (This is therefore
  5801.     one of the few questions in this section for which the answer is
  5802.     *not* "It's system-dependent.")  On older, pre-ANSI Unix
  5803.     systems, remove() may not exist, in which case you can try
  5804.     unlink().
  5805.  
  5806.     References: K&R2 Sec. B1.1 p. 242; ISO Sec. 7.9.4.1; H&S
  5807.     Sec. 15.15 p. 382; PCS Sec. 12 pp. 208,220-221; POSIX
  5808.     Sec. 5.5.1, Sec. 8.2.4.
  5809.  
  5810. 19.16b:    How do I copy files?
  5811.  
  5812. A:    Either use system() to invoke your operating system's copy
  5813.     utility (see question 19.27), or open the source and destination
  5814.     files (using fopen() or some lower-level file-opening system call),
  5815.     read characters or blocks of characters from the source file,
  5816.     and write them to the destination file.
  5817.  
  5818.     References: K&R Sec. 1, Sec. 7.
  5819.  
  5820. 19.17:    Why can't I open a file by its explicit path?  The call
  5821.  
  5822.         fopen("c:\newdir\file.dat", "r")
  5823.  
  5824.     is failing.
  5825.  
  5826. A:    The file you actually requested -- with the characters \n and \f
  5827.     in its name -- probably doesn't exist, and isn't what you
  5828.     thought you were trying to open.
  5829.  
  5830.     In character constants and string literals, the backslash \ is
  5831.     an escape character, giving special meaning to the character
  5832.     following it.  In order for literal backslashes in a pathname to
  5833.     be passed through to fopen() (or any other function) correctly,
  5834.     they have to be doubled, so that the first backslash in each
  5835.     pair quotes the second one:
  5836.  
  5837.         fopen("c:\\newdir\\file.dat", "r")
  5838.  
  5839.     Alternatively, under MS-DOS, it turns out that forward slashes
  5840.     are also accepted as directory separators, so you could use
  5841.  
  5842.         fopen("c:/newdir/file.dat", "r")
  5843.  
  5844.     (Note, by the way, that header file names mentioned in
  5845.     preprocessor #include directives are *not* string literals, so
  5846.     you may not have to worry about backslashes there.)
  5847.  
  5848. 19.18:    I'm getting an error, "Too many open files".  How can I increase
  5849.     the allowable number of simultaneously open files?
  5850.  
  5851. A:    There are typically at least two resource limitations on the
  5852.     number of simultaneously open files: the number of low-level
  5853.     "file descriptors" or "file handles" available in the operating
  5854.     system, and the number of FILE structures available in the stdio
  5855.     library.  Both must be sufficient.  Under MS-DOS systems, you
  5856.     can control the number of operating system file handles with a
  5857.     line in CONFIG.SYS.  Some compilers come with instructions (and
  5858.     perhaps a source file or two) for increasing the number of stdio
  5859.     FILE structures.
  5860.  
  5861. 19.20:    How can I read a directory in a C program?
  5862.  
  5863. A:    See if you can use the opendir() and readdir() functions, which
  5864.     are part of the POSIX standard and are available on most Unix
  5865.     variants.  Implementations also exist for MS-DOS, VMS, and other
  5866.     systems.  (MS-DOS also has FINDFIRST and FINDNEXT routines which
  5867.     do essentially the same thing.)  readdir() only returns file
  5868.     names; if you need more information about the file, try calling
  5869.     stat().  To match filenames to some wildcard pattern, see
  5870.     question 13.7.
  5871.  
  5872.     References: K&R2 Sec. 8.6 pp. 179-184; PCS Sec. 13 pp. 230-1;
  5873.     POSIX Sec. 5.1; Schumacher, ed., _Software Solutions in C_
  5874.     Sec. 8.
  5875.  
  5876. 19.22:    How can I find out how much memory is available?
  5877.  
  5878. A:    Your operating system may provide a routine which returns this
  5879.     information, but it's quite system-dependent.
  5880.  
  5881. 19.23:    How can I allocate arrays or structures bigger than 64K?
  5882.  
  5883. A:    A reasonable computer ought to give you transparent access to
  5884.     all available memory.  If you're not so lucky, you'll either
  5885.     have to rethink your program's use of memory, or use various
  5886.     system-specific techniques.
  5887.  
  5888.     64K is (still) a pretty big chunk of memory.  No matter how much
  5889.     memory your computer has available, it's asking a lot to be able
  5890.     to allocate huge amounts of it contiguously.  (The C Standard
  5891.     does not guarantee that single objects can be 32K or larger,
  5892.     or 64K for C9X.)  Often it's a good idea to use data
  5893.     structures which don't require that all memory be contiguous.
  5894.     For dynamically-allocated multidimensional arrays, you can
  5895.     use pointers to pointers, as illustrated in question 6.16.
  5896.     Instead of a large array of structures, you can use a linked
  5897.     list, or an array of pointers to structures.
  5898.  
  5899.     If you're using a PC-compatible (8086-based) system, and running
  5900.     up against a 64K or 640K limit, consider using "huge" memory
  5901.     model, or expanded or extended memory, or malloc variants such
  5902.     as halloc() or farmalloc(), or a 32-bit "flat" compiler (e.g.
  5903.     djgpp, see question 18.3), or some kind of a DOS extender, or
  5904.     another operating system.
  5905.  
  5906.     References: ISO Sec. 5.2.4.1; C9X Sec. 5.2.4.1.
  5907.  
  5908. 19.24:    What does the error message "DGROUP data allocation exceeds 64K"
  5909.     mean, and what can I do about it?  I thought that using large
  5910.     model meant that I could use more than 64K of data!
  5911.  
  5912. A:    Even in large memory models, MS-DOS compilers apparently toss
  5913.     certain data (strings, some initialized global or static
  5914.     variables) into a default data segment, and it's this segment
  5915.     that is overflowing.  Either use less global data, or, if you're
  5916.     already limiting yourself to reasonable amounts (and if the
  5917.     problem is due to something like the number of strings), you may
  5918.     be able to coax the compiler into not using the default data
  5919.     segment for so much.  Some compilers place only "small" data
  5920.     objects in the default data segment, and give you a way (e.g.
  5921.     the /Gt option under Microsoft compilers) to configure the
  5922.     threshold for "small."
  5923.  
  5924. 19.25:    How can I access memory (a memory-mapped device, or graphics
  5925.     memory) located at a certain address?
  5926.  
  5927. A:    Set a pointer, of the appropriate type, to the right number
  5928.     (using an explicit cast to assure the compiler that you really
  5929.     do intend this nonportable conversion):
  5930.  
  5931.         unsigned int *magicloc = (unsigned int *)0x12345678;
  5932.  
  5933.     Then, *magicloc refers to the location you want.  (Under MS-DOS,
  5934.     you may find a macro like MK_FP() handy for working with
  5935.     segments and offsets.)
  5936.  
  5937.     References: K&R1 Sec. A14.4 p. 210; K&R2 Sec. A6.6 p. 199; ISO
  5938.     Sec. 6.3.4; Rationale Sec. 3.3.4; H&S Sec. 6.2.7 pp. 171-2.
  5939.  
  5940. 19.27:    How can I invoke another program (a standalone executable,
  5941.     or an operating system command) from within a C program?
  5942.  
  5943. A:    Use the library function system(), which does exactly that.
  5944.     Note that system's return value is at best the command's exit
  5945.     status (although even that is not guaranteed), and usually has
  5946.     nothing to do with the output of the command.  Note also that
  5947.     system() accepts a single string representing the command to be
  5948.     invoked; if you need to build up a complex command line, you can
  5949.     use sprintf().  See also question 19.30.
  5950.  
  5951.     References: K&R1 Sec. 7.9 p. 157; K&R2 Sec. 7.8.4 p. 167,
  5952.     Sec. B6 p. 253; ISO Sec. 7.10.4.5; H&S Sec. 19.2 p. 407; PCS
  5953.     Sec. 11 p. 179.
  5954.  
  5955. 19.30:    How can I invoke another program or command and trap its output?
  5956.  
  5957. A:    Unix and some other systems provide a popen() function, which
  5958.     sets up a stdio stream on a pipe connected to the process
  5959.     running a command, so that the output can be read (or the input
  5960.     supplied).  (Also, remember to call pclose().)
  5961.  
  5962.     If you can't use popen(), you may be able to use system(), with
  5963.     the output going to a file which you then open and read.
  5964.  
  5965.     If you're using Unix and popen() isn't sufficient, you can learn
  5966.     about pipe(), dup(), fork(), and exec().
  5967.  
  5968.     (One thing that probably would *not* work, by the way, would be
  5969.     to use freopen().)
  5970.  
  5971.     References: PCS Sec. 11 p. 169.
  5972.  
  5973. 19.31:    How can my program discover the complete pathname to the
  5974.     executable from which it was invoked?
  5975.  
  5976. A:    argv[0] may contain all or part of the pathname, or it may
  5977.     contain nothing.  You may be able to duplicate the command
  5978.     language interpreter's search path logic to locate the
  5979.     executable if the name in argv[0] is present but incomplete.
  5980.     However, there is no guaranteed solution.
  5981.  
  5982.     References: K&R1 Sec. 5.11 p. 111; K&R2 Sec. 5.10 p. 115; ISO
  5983.     Sec. 5.1.2.2.1; H&S Sec. 20.1 p. 416.
  5984.  
  5985. 19.32:    How can I automatically locate a program's configuration files
  5986.     in the same directory as the executable?
  5987.  
  5988. A:    It's hard; see also question 19.31 above.  Even if you can
  5989.     figure out a workable way to do it, you might want to consider
  5990.     making the program's auxiliary (library) directory configurable,
  5991.     perhaps with an environment variable.  (It's especially
  5992.     important to allow variable placement of a program's
  5993.     configuration files when the program will be used by several
  5994.     people, e.g. on a multiuser system.)
  5995.  
  5996. 19.33:    How can a process change an environment variable in its caller?
  5997.  
  5998. A:    It may or may not be possible to do so at all.  Different
  5999.     operating systems implement global name/value functionality
  6000.     similar to the Unix environment in different ways.  Whether the
  6001.     "environment" can be usefully altered by a running program, and
  6002.     if so, how, is system-dependent.
  6003.  
  6004.     Under Unix, a process can modify its own environment (some
  6005.     systems provide setenv() or putenv() functions for the purpose),
  6006.     and the modified environment is generally passed on to child
  6007.     processes, but it is *not* propagated back to the parent
  6008.     process.  Under MS-DOS, it's possible to manipulate the master
  6009.     copy of the environment, but the required techniques are arcane.
  6010.     (See an MS-DOS FAQ list.)
  6011.  
  6012. 19.36:    How can I read in an object file and jump to locations in it?
  6013.  
  6014. A:    You want a dynamic linker or loader.  It may be possible to
  6015.     malloc some space and read in object files, but you have to know
  6016.     an awful lot about object file formats, relocation, etc.  Under
  6017.     BSD Unix, you could use system() and ld -A to do the linking for
  6018.     you.  Many versions of SunOS and System V have the -ldl library
  6019.     which allows object files to be dynamically loaded.  Under VMS,
  6020.     use LIB$FIND_IMAGE_SYMBOL.  GNU has a package called "dld".  See
  6021.     also question 15.13.
  6022.  
  6023. 19.37:    How can I implement a delay, or time a user's response, with sub-
  6024.     second resolution?
  6025.  
  6026. A:    Unfortunately, there is no portable way.  V7 Unix, and derived
  6027.     systems, provided a fairly useful ftime() function with
  6028.     resolution up to a millisecond, but it has disappeared from
  6029.     System V and POSIX.  Other routines you might look for on your
  6030.     system include clock(), delay(), gettimeofday(), msleep(),
  6031.     nap(), napms(), nanosleep(), setitimer(), sleep(), times(), and
  6032.     usleep().  (A function called wait(), however, is at least under
  6033.     Unix *not* what you want.)  The select() and poll() calls (if
  6034.     available) can be pressed into service to implement simple
  6035.     delays.  On MS-DOS machines, it is possible to reprogram the
  6036.     system timer and timer interrupts.
  6037.  
  6038.     Of these, only clock() is part of the ANSI Standard.  The
  6039.     difference between two calls to clock() gives elapsed execution
  6040.     time, and may even have subsecond resolution, if CLOCKS_PER_SEC
  6041.     is greater than 1.  However, clock() gives elapsed processor time
  6042.     used by the current program, which on a multitasking system may
  6043.     differ considerably from real time.
  6044.  
  6045.     If you're trying to implement a delay and all you have available
  6046.     is a time-reporting function, you can implement a CPU-intensive
  6047.     busy-wait, but this is only an option on a single-user, single-
  6048.     tasking machine as it is terribly antisocial to any other
  6049.     processes.  Under a multitasking operating system, be sure to
  6050.     use a call which puts your process to sleep for the duration,
  6051.     such as sleep() or select(), or pause() in conjunction with
  6052.     alarm() or setitimer().
  6053.  
  6054.     For really brief delays, it's tempting to use a do-nothing loop
  6055.     like
  6056.  
  6057.         long int i;
  6058.         for(i = 0; i < 1000000; i++)
  6059.             ;
  6060.  
  6061.     but resist this temptation if at all possible!  For one thing,
  6062.     your carefully-calculated delay loops will stop working properly
  6063.     next month when a faster processor comes out.  Perhaps worse, a
  6064.     clever compiler may notice that the loop does nothing and
  6065.     optimize it away completely.
  6066.  
  6067.     References: H&S Sec. 18.1 pp. 398-9; PCS Sec. 12 pp. 197-8,215-
  6068.     6; POSIX Sec. 4.5.2.
  6069.  
  6070. 19.38:    How can I trap or ignore keyboard interrupts like control-C?
  6071.  
  6072. A:    The basic step is to call signal(), either as
  6073.  
  6074.         #include <signal.h>
  6075.         signal(SIGINT, SIG_IGN);
  6076.  
  6077.     to ignore the interrupt signal, or as
  6078.  
  6079.         extern void func(int);
  6080.         signal(SIGINT, func);
  6081.  
  6082.     to cause control to transfer to function func() on receipt of an
  6083.     interrupt signal.
  6084.  
  6085.     On a multi-tasking system such as Unix, it's best to use a
  6086.     slightly more involved technique:
  6087.  
  6088.         extern void func(int);
  6089.         if(signal(SIGINT, SIG_IGN) != SIG_IGN)
  6090.             signal(SIGINT, func);
  6091.  
  6092.     The test and extra call ensure that a keyboard interrupt typed
  6093.     in the foreground won't inadvertently interrupt a program
  6094.     running in the background (and it doesn't hurt to code calls to
  6095.     signal() this way on any system).
  6096.  
  6097.     On some systems, keyboard interrupt handling is also a function
  6098.     of the mode of the terminal-input subsystem; see question 19.1.
  6099.     On some systems, checking for keyboard interrupts is only
  6100.     performed when the program is reading input, and keyboard
  6101.     interrupt handling may therefore depend on which input routines
  6102.     are being called (and *whether* any input routines are active at
  6103.     all).  On MS-DOS systems, setcbrk() or ctrlbrk() functions may
  6104.     also be involved.
  6105.  
  6106.     References: ISO Secs. 7.7,7.7.1; H&S Sec. 19.6 pp. 411-3; PCS
  6107.     Sec. 12 pp. 210-2; POSIX Secs. 3.3.1,3.3.4.
  6108.  
  6109. 19.39:    How can I handle floating-point exceptions gracefully?
  6110.  
  6111. A:    On many systems, you can define a function matherr() which will
  6112.     be called when there are certain floating-point errors, such as
  6113.     errors in the math routines in <math.h>.  You may also be able
  6114.     to use signal() (see question 19.38 above) to catch SIGFPE.  See
  6115.     also question 14.9.
  6116.  
  6117.     References: Rationale Sec. 4.5.1.
  6118.  
  6119. 19.40:    How do I...  Use sockets?  Do networking?  Write client/server
  6120.     applications?
  6121.  
  6122. A:    All of these questions are outside of the scope of this list and
  6123.     have much more to do with the networking facilities which you
  6124.     have available than they do with C.  Good books on the subject
  6125.     are Douglas Comer's three-volume _Internetworking with TCP/IP_
  6126.     and W. R. Stevens's _UNIX Network Programming_.  (There is also
  6127.     plenty of information out on the net itself, including the
  6128.     "Unix Socket FAQ" at http://kipper.york.ac.uk/~vic/sock-faq/ .)
  6129.  
  6130. 19.40b:    How do I...  Use BIOS calls?  Write ISR's?  Create TSR's?
  6131.  
  6132. A:    These are very particular to specific systems (PC compatibles
  6133.     running MS-DOS, most likely).  You'll get much better
  6134.     information in a specific newsgroup such as
  6135.     comp.os.msdos.programmer or its FAQ list; another excellent
  6136.     resource is Ralf Brown's interrupt list.
  6137.  
  6138. 19.40c:    I'm trying to compile this program, but the compiler is
  6139.     complaining that "union REGS" is undefined, and the linker
  6140.     is complaining that int86() is undefined.
  6141.  
  6142. A:    Those have to do with MS-DOS interrupt programming.  They don't
  6143.     exist on other systems.
  6144.  
  6145. 19.41:    But I can't use all these nonstandard, system-dependent
  6146.     functions, because my program has to be ANSI compatible!
  6147.  
  6148. A:    You're out of luck.  Either you misunderstood your requirement,
  6149.     or it's an impossible one to meet.  ANSI/ISO Standard C simply
  6150.     does not define ways of doing these things; it is a language
  6151.     standard, not an operating system standard.  An international
  6152.     standard which does address many of these issues is POSIX
  6153.     (IEEE 1003.1, ISO/IEC 9945-1), and many operating systems (not
  6154.     just Unix) now have POSIX-compatible programming interfaces.
  6155.  
  6156.     It is possible, and desirable, for *most* of a program to be
  6157.     ANSI-compatible, deferring the system-dependent functionality to
  6158.     a few routines in a few files which are rewritten for each
  6159.     system ported to.
  6160.  
  6161.  
  6162. Section 20. Miscellaneous
  6163.  
  6164. 20.1:    How can I return multiple values from a function?
  6165.  
  6166. A:    Either pass pointers to several locations which the function can
  6167.     fill in, or have the function return a structure containing the
  6168.     desired values, or (in a pinch) consider global variables.  See
  6169.     also questions 2.7, 4.8, and 7.5a.
  6170.  
  6171. 20.3:    How do I access command-line arguments?
  6172.  
  6173. A:    They are pointed to by the argv array with which main() is
  6174.     called.  See also questions 8.2, 13.7, and 19.20.
  6175.  
  6176.     References: K&R1 Sec. 5.11 pp. 110-114; K&R2 Sec. 5.10 pp. 114-
  6177.     118; ISO Sec. 5.1.2.2.1; H&S Sec. 20.1 p. 416; PCS Sec. 5.6 pp.
  6178.     81-2, Sec. 11 p. 159, pp. 339-40 Appendix F; Schumacher, ed.,
  6179.     _Software Solutions in C_ Sec. 4 pp. 75-85.
  6180.  
  6181. 20.5:    How can I write data files which can be read on other machines
  6182.     with different word size, byte order, or floating point formats?
  6183.  
  6184. A:    The most portable solution is to use text files (usually ASCII),
  6185.     written with fprintf() and read with fscanf() or the like.
  6186.     (Similar advice also applies to network protocols.)  Be
  6187.     skeptical of arguments which imply that text files are too big,
  6188.     or that reading and writing them is too slow.  Not only is their
  6189.     efficiency frequently acceptable in practice, but the advantages
  6190.     of being able to interchange them easily between machines, and
  6191.     manipulate them with standard tools, can be overwhelming.
  6192.  
  6193.     If you must use a binary format, you can improve portability,
  6194.     and perhaps take advantage of prewritten I/O libraries, by
  6195.     making use of standardized formats such as Sun's XDR (RFC 1014),
  6196.     OSI's ASN.1 (referenced in CCITT X.409 and ISO 8825 "Basic
  6197.     Encoding Rules"), CDF, netCDF, or HDF.  See also questions 2.12
  6198.     and 12.38.
  6199.  
  6200.     References: PCS Sec. 6 pp. 86, 88.
  6201.  
  6202. 20.6:    If I have a char * variable pointing to the name of a function,
  6203.     how can I call that function?
  6204.  
  6205. A:    The most straightforward thing to do is to maintain a
  6206.     correspondence table of names and function pointers:
  6207.  
  6208.         int func(), anotherfunc();
  6209.  
  6210.         struct { char *name; int (*funcptr)(); } symtab[] = {
  6211.             "func",        func,
  6212.             "anotherfunc",    anotherfunc,
  6213.         };
  6214.  
  6215.     Then, search the table for the name, and call via the associated
  6216.     function pointer.  See also questions 2.15, 18.14, and 19.36.
  6217.  
  6218.     References: PCS Sec. 11 p. 168.
  6219.  
  6220. 20.8:    How can I implement sets or arrays of bits?
  6221.  
  6222. A:    Use arrays of char or int, with a few macros to access the
  6223.     desired bit at the proper index.  Here are some simple macros to
  6224.     use with arrays of char:
  6225.  
  6226.         #include <limits.h>        /* for CHAR_BIT */
  6227.  
  6228.         #define BITMASK(b) (1 << ((b) % CHAR_BIT))
  6229.         #define BITSLOT(b) ((b) / CHAR_BIT)
  6230.         #define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
  6231.         #define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))
  6232.  
  6233.     (If you don't have <limits.h>, try using 8 for CHAR_BIT.)
  6234.  
  6235.     References: H&S Sec. 7.6.7 pp. 211-216.
  6236.  
  6237. 20.9:    How can I determine whether a machine's byte order is big-endian
  6238.     or little-endian?
  6239.  
  6240. A:    One way is to use a pointer:
  6241.  
  6242.         int x = 1;
  6243.         if(*(char *)&x == 1)
  6244.             printf("little-endian\n");
  6245.         else    printf("big-endian\n");
  6246.  
  6247.     It's also possible to use a union.
  6248.  
  6249.     See also question 10.16.
  6250.  
  6251.     References: H&S Sec. 6.1.2 pp. 163-4.
  6252.  
  6253. 20.10:    How can I convert integers to binary or hexadecimal?
  6254.  
  6255. A:    Make sure you really know what you're asking.  Integers are
  6256.     stored internally in binary, although for most purposes it is
  6257.     not incorrect to think of them as being in octal, decimal, or
  6258.     hexadecimal, whichever is convenient.  The base in which a
  6259.     number is expressed matters only when that number is read in
  6260.     from or written out to the outside world.
  6261.  
  6262.     In source code, a non-decimal base is indicated by a leading 0
  6263.     or 0x (for octal or hexadecimal, respectively).  During I/O, the
  6264.     base of a formatted number is controlled in the printf and scanf
  6265.     family of functions by the choice of format specifier (%d, %o,
  6266.     %x, etc.) and in the strtol() and strtoul() functions by the
  6267.     third argument.  If you need to output numeric strings in
  6268.     arbitrary bases, you'll have to supply your own function to do
  6269.     so (it will essentially be the inverse of strtol).  During
  6270.     *binary* I/O, however, the base again becomes immaterial.
  6271.  
  6272.     For more information about "binary" I/O, see question 2.11.
  6273.     See also questions 8.6 and 13.1.
  6274.  
  6275.     References: ISO Secs. 7.10.1.5,7.10.1.6.
  6276.  
  6277. 20.11:    Can I use base-2 constants (something like 0b101010)?
  6278.     Is there a printf() format for binary?
  6279.  
  6280. A:    No, on both counts.  You can convert base-2 string
  6281.     representations to integers with strtol().  See also question
  6282.     20.10.
  6283.  
  6284. 20.12:    What is the most efficient way to count the number of bits which
  6285.     are set in an integer?
  6286.  
  6287. A:    Many "bit-fiddling" problems like this one can be sped up and
  6288.     streamlined using lookup tables (but see question 20.13 below).
  6289.  
  6290. 20.13:    What's the best way of making my program efficient?
  6291.  
  6292. A:    By picking good algorithms, implementing them carefully, and
  6293.     making sure that your program isn't doing any extra work.  For
  6294.     example, the most microoptimized character-copying loop in the
  6295.     world will be beat by code which avoids having to copy
  6296.     characters at all.
  6297.  
  6298.     When worrying about efficiency, it's important to keep several
  6299.     things in perspective.  First of all, although efficiency is an
  6300.     enormously popular topic, it is not always as important as
  6301.     people tend to think it is.  Most of the code in most programs
  6302.     is not time-critical.  When code is not time-critical, it is
  6303.     usually more important that it be written clearly and portably
  6304.     than that it be written maximally efficiently.  (Remember that
  6305.     computers are very, very fast, and that seemingly "inefficient"
  6306.     code may be quite efficiently compilable, and run without
  6307.     apparent delay.)
  6308.  
  6309.     It is notoriously difficult to predict what the "hot spots" in a
  6310.     program will be.  When efficiency is a concern, it is important
  6311.     to use profiling software to determine which parts of the
  6312.     program deserve attention.  Often, actual computation time is
  6313.     swamped by peripheral tasks such as I/O and memory allocation,
  6314.     which can be sped up by using buffering and caching techniques.
  6315.  
  6316.     Even for code that *is* time-critical, one of the least
  6317.     effective optimization techniques is to fuss with the coding
  6318.     details.  Many of the "efficient coding tricks" which are
  6319.     frequently suggested (e.g. substituting shift operators for
  6320.     multiplication by powers of two) are performed automatically by
  6321.     even simpleminded compilers.  Heavyhanded optimization attempts
  6322.     can make code so bulky that performance is actually degraded,
  6323.     and are rarely portable (i.e. they may speed things up on one
  6324.     machine but slow them down on another).  In any case, tweaking
  6325.     the coding usually results in at best linear performance
  6326.     improvements; the big payoffs are in better algorithms.
  6327.  
  6328.     For more discussion of efficiency tradeoffs, as well as good
  6329.     advice on how to improve efficiency when it is important, see
  6330.     chapter 7 of Kernighan and Plauger's _The Elements of
  6331.     Programming Style_, and Jon Bentley's _Writing Efficient
  6332.     Programs_.
  6333.  
  6334. 20.14:    Are pointers really faster than arrays?  How much do function
  6335.     calls slow things down?  Is ++i faster than i = i + 1?
  6336.  
  6337. A:    Precise answers to these and many similar questions depend of
  6338.     course on the processor and compiler in use.  If you simply must
  6339.     know, you'll have to time test programs carefully.  (Often the
  6340.     differences are so slight that hundreds of thousands of
  6341.     iterations are required even to see them.  Check the compiler's
  6342.     assembly language output, if available, to see if two purported
  6343.     alternatives aren't compiled identically.)
  6344.  
  6345.     It is "usually" faster to march through large arrays with
  6346.     pointers rather than array subscripts, but for some processors
  6347.     the reverse is true.
  6348.  
  6349.     Function calls, though obviously incrementally slower than in-
  6350.     line code, contribute so much to modularity and code clarity
  6351.     that there is rarely good reason to avoid them.
  6352.  
  6353.     Before rearranging expressions such as i = i + 1, remember that
  6354.     you are dealing with a compiler, not a keystroke-programmable
  6355.     calculator.  Any decent compiler will generate identical code
  6356.     for ++i, i += 1, and i = i + 1.  The reasons for using ++i or
  6357.     i += 1 over i = i + 1 have to do with style, not efficiency.
  6358.     (See also question 3.12.)
  6359.  
  6360. 20.15b:    People claim that optimizing compilers are good and that we no
  6361.     longer have to write things in assembler for speed, but my
  6362.     compiler can't even replace i/=2 with a shift.
  6363.  
  6364. A:    Was i signed or unsigned?  If it was signed, a shift is not
  6365.     equivalent (hint: think about the result if i is negative and
  6366.     odd), so the compiler was correct not to use it.
  6367.  
  6368. 20.15c:    How can I swap two values without using a temporary?
  6369.  
  6370. A:    The standard hoary old assembly language programmer's trick is:
  6371.  
  6372.         a ^= b;
  6373.         b ^= a;
  6374.         a ^= b;
  6375.  
  6376.     But this sort of code has little place in modern, HLL
  6377.     programming.  Temporary variables are essentially free,
  6378.     and the idiomatic code using three assignments, namely
  6379.  
  6380.         int t = a;
  6381.         a = b;
  6382.         b = t;
  6383.  
  6384.     is not only clearer to the human reader, it is more likely to be
  6385.     recognized by the compiler and turned into the most-efficient
  6386.     code (e.g. using a swap instruction, if available).  The latter
  6387.     code is obviously also amenable to use with pointers and
  6388.     floating-point values, unlike the XOR trick.  See also questions
  6389.     3.3b and 10.3.
  6390.  
  6391. 20.17:    Is there a way to switch on strings?
  6392.  
  6393. A:    Not directly.  Sometimes, it's appropriate to use a separate
  6394.     function to map strings to integer codes, and then switch on
  6395.     those.  Otherwise, of course, you can fall back on strcmp() and
  6396.     a conventional if/else chain.  See also questions 10.12, 20.18,
  6397.     and 20.29.
  6398.  
  6399.     References: K&R1 Sec. 3.4 p. 55; K&R2 Sec. 3.4 p. 58; ISO
  6400.     Sec. 6.6.4.2; H&S Sec. 8.7 p. 248.
  6401.  
  6402. 20.18:    Is there a way to have non-constant case labels (i.e. ranges or
  6403.     arbitrary expressions)?
  6404.  
  6405. A:    No.  The switch statement was originally designed to be quite
  6406.     simple for the compiler to translate, therefore case labels are
  6407.     limited to single, constant, integral expressions.  You *can*
  6408.     attach several case labels to the same statement, which will let
  6409.     you cover a small range if you don't mind listing all cases
  6410.     explicitly.
  6411.  
  6412.     If you want to select on arbitrary ranges or non-constant
  6413.     expressions, you'll have to use an if/else chain.
  6414.  
  6415.     See also question 20.17.
  6416.  
  6417.     References: K&R1 Sec. 3.4 p. 55; K&R2 Sec. 3.4 p. 58; ISO
  6418.     Sec. 6.6.4.2; Rationale Sec. 3.6.4.2; H&S Sec. 8.7 p. 248.
  6419.  
  6420. 20.19:    Are the outer parentheses in return statements really optional?
  6421.  
  6422. A:    Yes.
  6423.  
  6424.     Long ago, in the early days of C, they were required, and just
  6425.     enough people learned C then, and wrote code which is still in
  6426.     circulation, that the notion that they might still be required
  6427.     is widespread.
  6428.  
  6429.     (As it happens, parentheses are optional with the sizeof
  6430.     operator, too, under certain circumstances.)
  6431.  
  6432.     References: K&R1 Sec. A18.3 p. 218; ISO Sec. 6.3.3, Sec. 6.6.6;
  6433.     H&S Sec. 8.9 p. 254.
  6434.  
  6435. 20.20:    Why don't C comments nest?  How am I supposed to comment out
  6436.     code containing comments?  Are comments legal inside quoted
  6437.     strings?
  6438.  
  6439. A:    C comments don't nest mostly because PL/I's comments, which C's
  6440.     are borrowed from, don't either.  Therefore, it is usually
  6441.     better to "comment out" large sections of code, which might
  6442.     contain comments, with #ifdef or #if 0 (but see question 11.19).
  6443.  
  6444.     The character sequences /* and */ are not special within double-
  6445.     quoted strings, and do not therefore introduce comments, because
  6446.     a program (particularly one which is generating C code as
  6447.     output) might want to print them.
  6448.  
  6449.     Note also that // comments, as in C++, are not yet legal in C,
  6450.     so it's not a good idea to use them in C programs (even if your
  6451.     compiler supports them as an extension).
  6452.  
  6453.     References: K&R1 Sec. A2.1 p. 179; K&R2 Sec. A2.2 p. 192; ISO
  6454.     Sec. 6.1.9, Annex F; Rationale Sec. 3.1.9; H&S Sec. 2.2 pp. 18-
  6455.     9; PCS Sec. 10 p. 130.
  6456.  
  6457. 20.20b:    Is C a great language, or what?  Where else could you write
  6458.     something like a+++++b ?
  6459.  
  6460. A:    Well, you can't meaningfully write it in C, either.
  6461.     The rule for lexical analysis is that at each point during a
  6462.     straightforward left-to-right scan, the longest possible token
  6463.     is determined, without regard to whether the resulting sequence
  6464.     of tokens makes sense.  The fragment in the question is
  6465.     therefore interpreted as
  6466.  
  6467.         a ++ ++ + b
  6468.  
  6469.     and cannot be parsed as a valid expression.
  6470.  
  6471.     References: K&R1 Sec. A2 p. 179; K&R2 Sec. A2.1 p. 192; ISO
  6472.     Sec. 6.1; H&S Sec. 2.3 pp. 19-20.
  6473.  
  6474. 20.24:    Why doesn't C have nested functions?
  6475.  
  6476. A:    It's not trivial to implement nested functions such that they
  6477.     have the proper access to local variables in the containing
  6478.     function(s), so they were deliberately left out of C as a
  6479.     simplification.  (gcc does allow them, as an extension.)  For
  6480.     many potential uses of nested functions (e.g. qsort comparison
  6481.     functions), an adequate if slightly cumbersome solution is to
  6482.     use an adjacent function with static declaration, communicating
  6483.     if necessary via a few static variables.  (A cleaner solution,
  6484.     though unsupported by qsort(), is to pass around a pointer to
  6485.     a structure containing the necessary context.)
  6486.  
  6487. 20.24b:    What is assert() and when would I use it?
  6488.  
  6489. A:    It is a macro, defined in <assert.h>, for testing "assertions".
  6490.     An assertion essentially documents an assumption being made by
  6491.     the programmer, an assumption which, if violated, would indicate
  6492.     a serious programming error.  For example, a function which was
  6493.     supposed to be called with a non-null pointer could write
  6494.  
  6495.         assert(p != NULL);
  6496.  
  6497.     A failed assertion terminates the program.  Assertions should
  6498.     *not* be used to catch expected errors, such as malloc() or
  6499.     fopen() failures.
  6500.  
  6501.     References: K&R2 Sec. B6 pp. 253-4; ISO Sec. 7.2; H&S Sec. 19.1
  6502.     p. 406.
  6503.  
  6504. 20.25:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  6505.     from C?  (And vice versa?)
  6506.  
  6507. A:    The answer is entirely dependent on the machine and the specific
  6508.     calling sequences of the various compilers in use, and may not
  6509.     be possible at all.  Read your compiler documentation very
  6510.     carefully; sometimes there is a "mixed-language programming
  6511.     guide," although the techniques for passing arguments and
  6512.     ensuring correct run-time startup are often arcane.  More
  6513.     information may be found in FORT.gz by Glenn Geers, available
  6514.     via anonymous ftp from suphys.physics.su.oz.au in the src
  6515.     directory.
  6516.  
  6517.     cfortran.h, a C header file, simplifies C/FORTRAN interfacing on
  6518.     many popular machines.  It is available via anonymous ftp from
  6519.     zebra.desy.de or at http://www-zeus.desy.de/~burow .
  6520.  
  6521.     In C++, a "C" modifier in an external function declaration
  6522.     indicates that the function is to be called using C calling
  6523.     conventions.
  6524.  
  6525.     References: H&S Sec. 4.9.8 pp. 106-7.
  6526.  
  6527. 20.26:    Does anyone know of a program for converting Pascal or FORTRAN
  6528.     (or LISP, Ada, awk, "Old" C, ...) to C?
  6529.  
  6530. A:    Several freely distributable programs are available:
  6531.  
  6532.     p2c    A Pascal to C converter written by Dave Gillespie,
  6533.         posted to comp.sources.unix in March, 1990 (Volume 21);
  6534.         also available by anonymous ftp from
  6535.         csvax.cs.caltech.edu, file pub/p2c-1.20.tar.Z .
  6536.  
  6537.     ptoc    Another Pascal to C converter, this one written in
  6538.         Pascal (comp.sources.unix, Volume 10, also patches in
  6539.         Volume 13?).
  6540.  
  6541.     f2c    A FORTRAN to C converter jointly developed by people
  6542.         from Bell Labs, Bellcore, and Carnegie Mellon.  To find
  6543.         out more about f2c, send the mail message "send index
  6544.         from f2c" to netlib@research.att.com or research!netlib.
  6545.         (It is also available via anonymous ftp on
  6546.         netlib.att.com, in directory netlib/f2c.)
  6547.  
  6548.     This FAQ list's maintainer also has available a list of a few
  6549.     other commercial translation products, and some for more obscure
  6550.     languages.
  6551.  
  6552.     See also questions 11.31 and 18.16.
  6553.  
  6554. 20.27:    Is C++ a superset of C?  Can I use a C++ compiler to compile C
  6555.     code?
  6556.  
  6557. A:    C++ was derived from C, and is largely based on it, but there
  6558.     are some legal C constructs which are not legal C++.
  6559.     Conversely, ANSI C inherited several features from C++,
  6560.     including prototypes and const, so neither language is really a
  6561.     subset or superset of the other; the two also define the meaning
  6562.     of some common constructs differently.  In spite of the
  6563.     differences, many C programs will compile correctly in a C++
  6564.     environment, and many recent compilers offer both C and C++
  6565.     compilation modes.  See also questions 8.9 and 20.20.
  6566.  
  6567.     References: H&S p. xviii, Sec. 1.1.5 p. 6, Sec. 2.8 pp. 36-7,
  6568.     Sec. 4.9 pp. 104-107.
  6569.  
  6570. 20.28:    I need a sort of an "approximate" strcmp routine, for comparing
  6571.     two strings for close, but not necessarily exact, equality.
  6572.  
  6573. A:    Some nice information and algorithms having to do with
  6574.     approximate string matching, as well as a useful bibliography,
  6575.     can be found in Sun Wu and Udi Manber's paper "AGREP -- A Fast
  6576.     Approximate Pattern-Matching Tool."
  6577.  
  6578.     Another approach involves the "soundex" algorithm, which maps
  6579.     similar-sounding words to the same codes.  Soundex was designed
  6580.     for discovering similar-sounding names (for telephone directory
  6581.     assistance, as it happens), but it can be pressed into service
  6582.     for processing arbitrary words.
  6583.  
  6584.     References: Knuth Sec. 6 pp. 391-2 Volume 3; Wu and Manber,
  6585.     "AGREP -- A Fast Approximate Pattern-Matching Tool" .
  6586.  
  6587. 20.29:    What is hashing?
  6588.  
  6589. A:    Hashing is the process of mapping strings to integers, usually
  6590.     in a relatively small range.  A "hash function" maps a string
  6591.     (or some other data structure) to a bounded number (the "hash
  6592.     bucket") which can more easily be used as an index in an array,
  6593.     or for performing repeated comparisons.  (Obviously, a mapping
  6594.     from a potentially huge set of strings to a small set of
  6595.     integers will not be unique.  Any algorithm using hashing
  6596.     therefore has to deal with the possibility of "collisions.")
  6597.     Many hashing functions and related algorithms have been
  6598.     developed; a full treatment is beyond the scope of this list.
  6599.  
  6600.     References: K&R2 Sec. 6.6; Knuth Sec. 6.4 pp. 506-549 Volume 3;
  6601.     Sedgewick Sec. 16 pp. 231-244.
  6602.  
  6603. 20.31:    How can I find the day of the week given the date?
  6604.  
  6605. A:    Use mktime() or localtime() (see questions 13.13 and 13.14, but
  6606.     beware of DST adjustments if tm_hour is 0), or Zeller's
  6607.     congruence (see the sci.math FAQ list), or this elegant code by
  6608.     Tomohiko Sakamoto:
  6609.  
  6610.         int dayofweek(int y, int m, int d)    /* 0 = Sunday */
  6611.         {
  6612.             static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
  6613.             y -= m < 3;
  6614.             return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
  6615.         }
  6616.  
  6617.     See also questions 13.14 and 20.32.
  6618.  
  6619.     References: ISO Sec. 7.12.2.3.
  6620.  
  6621. 20.32:    Will 2000 be a leap year?  Is (year % 4 == 0) an accurate test
  6622.     for leap years?
  6623.  
  6624. A:    Yes and no, respectively.  The full expression for the present
  6625.     Gregorian calendar is
  6626.  
  6627.         year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
  6628.  
  6629.     See a good astronomical almanac or other reference for details.
  6630.     (To forestall an eternal debate: references which claim the
  6631.     existence of a 4000-year rule are wrong.)  See also questions
  6632.     13.14 and 13.14b.
  6633.  
  6634. 20.34:    Here's a good puzzle: how do you write a program which produces
  6635.     its own source code as output?
  6636.  
  6637. A:    It is actually quite difficult to write a self-reproducing
  6638.     program that is truly portable, due particularly to quoting and
  6639.     character set difficulties.
  6640.  
  6641.     Here is a classic example (which ought to be presented on one
  6642.     line, although it will fix itself the first time it's run):
  6643.  
  6644.         char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
  6645.         main(){printf(s,34,s,34);}
  6646.  
  6647.     (This program, like many of the genre, neglects to #include
  6648.     <stdio.h>, and assumes that the double-quote character " has the
  6649.     value 34, as it does in ASCII.)
  6650.  
  6651. 20.35:    What is "Duff's Device"?
  6652.  
  6653. A:    It's a devastatingly deviously unrolled byte-copying loop,
  6654.     devised by Tom Duff while he was at Lucasfilm.  In its "classic"
  6655.     form, it looks like:
  6656.  
  6657.         register n = (count + 7) / 8;    /* count > 0 assumed */
  6658.         switch (count % 8)
  6659.         {
  6660.         case 0:    do {    *to = *from++;
  6661.         case 7:        *to = *from++;
  6662.         case 6:        *to = *from++;
  6663.         case 5:        *to = *from++;
  6664.         case 4:        *to = *from++;
  6665.         case 3:        *to = *from++;
  6666.         case 2:        *to = *from++;
  6667.         case 1:        *to = *from++;
  6668.                   } while (--n > 0);
  6669.         }
  6670.  
  6671.     where count bytes are to be copied from the array pointed to by
  6672.     from to the memory location pointed to by to (which is a memory-
  6673.     mapped device output register, which is why to isn't
  6674.     incremented).  It solves the problem of handling the leftover
  6675.     bytes (when count isn't a multiple of 8) by interleaving a
  6676.     switch statement with the loop which copies bytes 8 at a time.
  6677.     (Believe it or not, it *is* legal to have case labels buried
  6678.     within blocks nested in a switch statement like this.  In his
  6679.     announcement of the technique to C's developers and the world,
  6680.     Duff noted that C's switch syntax, in particular its "fall
  6681.     through" behavior, had long been controversial, and that "This
  6682.     code forms some sort of argument in that debate, but I'm not
  6683.     sure whether it's for or against.")
  6684.  
  6685. 20.36:    When will the next International Obfuscated C Code Contest
  6686.     (IOCCC) be held?  How can I get a copy of the current and
  6687.     previous winning entries?
  6688.  
  6689. A:    The contest is in a state of flux; see
  6690.     http://www.ioccc.org/index.html for current details.
  6691.  
  6692.     Contest winners are usually announced at a Usenix conference,
  6693.     and are posted to the net sometime thereafter.  Winning entries
  6694.     from previous years (back to 1984) are archived at ftp.uu.net
  6695.     (see question 18.16) under the directory pub/ioccc/; see also
  6696.     http://www.ioccc.org/index.html .
  6697.  
  6698. 20.37:    What was the entry keyword mentioned in K&R1?
  6699.  
  6700. A:    It was reserved to allow the possibility of having functions
  6701.     with multiple, differently-named entry points, a la FORTRAN.  It
  6702.     was not, to anyone's knowledge, ever implemented (nor does
  6703.     anyone remember what sort of syntax might have been imagined for
  6704.     it).  It has been withdrawn, and is not a keyword in ANSI C.
  6705.     (See also question 1.12.)
  6706.  
  6707.     References: K&R2 p. 259 Appendix C.
  6708.  
  6709. 20.38:    Where does the name "C" come from, anyway?
  6710.  
  6711. A:    C was derived from Ken Thompson's experimental language B, which
  6712.     was inspired by Martin Richards's BCPL (Basic Combined
  6713.     Programming Language), which was a simplification of CPL
  6714.     (Cambridge Programming Language).  For a while, there was
  6715.     speculation that C's successor might be named P (the third
  6716.     letter in BCPL) instead of D, but of course the most visible
  6717.     descendant language today is C++.
  6718.  
  6719. 20.39:    How do you pronounce "char"?
  6720.  
  6721. A:    You can pronounce the C keyword "char" in at least three ways:
  6722.     like the English words "char," "care," or "car" (or maybe even
  6723.     "character"); the choice is arbitrary.
  6724.  
  6725. 20.39b:    What do "lvalue" and "rvalue" mean?
  6726.  
  6727. A:    Simply speaking, an "lvalue" is an expression that could appear
  6728.     on the left-hand sign of an assignment; you can also think of it
  6729.     as denoting an object that has a location.  (But see question
  6730.     6.7 concerning arrays.)  An "rvalue" is any expression that has
  6731.     a value (and that can therefore appear on the right-hand sign of
  6732.     an assignment).
  6733.  
  6734. 20.40:    Where can I get extra copies of this list?
  6735.     What about back issues?
  6736.  
  6737. A:    An up-to-date copy may be obtained from ftp.eskimo.com in
  6738.     directory u/s/scs/C-faq/.  You can also just pull it off the
  6739.     net; it is normally posted to comp.lang.c on the first of each
  6740.     month, with an Expires: line which should keep it around all
  6741.     month.  A parallel, abridged version is available (and posted),
  6742.     as is a list of changes accompanying each significantly updated
  6743.     version.
  6744.  
  6745.     The various versions of this list are also posted to the
  6746.     newsgroups comp.answers and news.answers .  Several sites
  6747.     archive news.answers postings and other FAQ lists, including
  6748.     this one; two sites are rtfm.mit.edu (directories
  6749.     pub/usenet/news.answers/C-faq/ and pub/usenet/comp.lang.c/) and
  6750.     ftp.uu.net (directory usenet/news.answers/C-faq/).  If you don't
  6751.     have ftp access, a mailserver at rtfm.mit.edu can mail you FAQ
  6752.     lists: send a message containing the single word "help" to
  6753.     mail-server@rtfm.mit.edu .  See the meta-FAQ list in
  6754.     news.answers for more information.
  6755.  
  6756.     A hypertext (HTML) version of this FAQ list is available on the
  6757.     World-Wide Web; the URL is http://www.eskimo.com/~scs/C-faq/top.html .
  6758.     A comprehensive site which references all Usenet FAQ lists is
  6759.     http://www.faqs.org/faqs/ .
  6760.  
  6761.     An extended version of this FAQ list has been published by
  6762.     Addison-Wesley as _C Programming FAQs: Frequently Asked
  6763.     Questions_ (ISBN 0-201-84519-9).  An errata list is at
  6764.     http://www.eskimo.com/~scs/C-faq/book/Errata.html and on
  6765.     ftp.eskimo.com in u/s/scs/ftp/C-faq/book/Errata .
  6766.  
  6767.     This list is an evolving document containing questions which
  6768.     have been Frequent since before the Great Renaming; it is not
  6769.     just a collection of this month's interesting questions.  Older
  6770.     copies are obsolete and don't contain much, except the
  6771.     occasional typo, that the current list doesn't.
  6772.  
  6773.  
  6774. Bibliography
  6775.  
  6776. American National Standards Institute, _American National Standard for
  6777. Information Systems -- Programming Language -- C_, ANSI X3.159-1989
  6778. (see question 11.2).  [ANSI]
  6779.  
  6780. American National Standards Institute, _Rationale for American National
  6781. Standard for Information Systems -- Programming Language -- C_
  6782. (see question 11.2).  [Rationale]
  6783.  
  6784. Jon Bentley, _Writing Efficient Programs_, Prentice-Hall, 1982,
  6785. ISBN 0-13-970244-X.
  6786.  
  6787. David Burki, "Date Conversions," _The C Users Journal_, February 1993,
  6788. pp. 29-34.
  6789.  
  6790. Ian F. Darwin, _Checking C Programs with lint_, O'Reilly, 1988,
  6791. ISBN 0-937175-30-7.
  6792.  
  6793. David Goldberg, "What Every Computer Scientist Should Know about
  6794. Floating-Point Arithmetic," _ACM Computing Surveys_, Vol. 23 #1,
  6795. March, 1991, pp. 5-48.
  6796.  
  6797. Samuel P. Harbison and Guy L. Steele, Jr., _C: A Reference Manual_,
  6798. Fourth Edition, Prentice-Hall, 1995, ISBN 0-13-326224-3.  [H&S]
  6799.  
  6800. Mark R. Horton, _Portable C Software_, Prentice Hall, 1990,
  6801. ISBN 0-13-868050-7.  [PCS]
  6802.  
  6803. Institute of Electrical and Electronics Engineers, _Portable Operating
  6804. System Interface (POSIX) -- Part 1: System Application Program Interface
  6805. (API) [C Language]_, IEEE Std. 1003.1, ISO/IEC 9945-1.
  6806.  
  6807. International Organization for Standardization, ISO 9899:1990
  6808. (see question 11.2).  [ISO]
  6809.  
  6810. International Organization for Standardization, WG14/N794 Working Draft
  6811. (see questions 11.1 and 11.2b).  [C9X]
  6812.  
  6813. Brian W. Kernighan and P.J. Plauger, _The Elements of Programming
  6814. Style_, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5.
  6815.  
  6816. Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_,
  6817. Prentice-Hall, 1978, ISBN 0-13-110163-3.  [K&R1]
  6818.  
  6819. Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_,
  6820. Second Edition, Prentice Hall, 1988, ISBN 0-13-110362-8, 0-13-110370-9.
  6821. (See also question 18.10.) [K&R2]
  6822.  
  6823. Donald E. Knuth, _The Art of Computer Programming_.  Volume 1:
  6824. _Fundamental Algorithms_, Second Edition, Addison-Wesley, 1973, ISBN
  6825. 0-201-03809-9.  Volume 2: _Seminumerical Algorithms_, Second Edition,
  6826. Addison-Wesley, 1981, ISBN 0-201-03822-6.  Volume 3: _Sorting and
  6827. Searching_, Addison-Wesley, 1973, ISBN 0-201-03803-X.  (New editions
  6828. are coming out!) [Knuth]
  6829.  
  6830. Andrew Koenig, _C Traps and Pitfalls_, Addison-Wesley, 1989,
  6831. ISBN 0-201-17928-8.  [CT&P]
  6832.  
  6833. G. Marsaglia and T.A. Bray, "A Convenient Method for Generating Normal
  6834. Variables," _SIAM Review_, Vol. 6 #3, July, 1964.
  6835.  
  6836. Stephen K. Park and Keith W. Miller, "Random Number Generators: Good
  6837. Ones are Hard to Find," _Communications of the ACM_, Vol. 31 #10,
  6838. October, 1988, pp. 1192-1201 (also technical correspondence August,
  6839. 1989, pp. 1020-1024, and July, 1993, pp. 108-110).
  6840.  
  6841. P.J. Plauger, _The Standard C Library_, Prentice Hall, 1992,
  6842. ISBN 0-13-131509-9.
  6843.  
  6844. Thomas Plum, _C Programming Guidelines_, Second Edition, Plum Hall,
  6845. 1989, ISBN 0-911537-07-4.
  6846.  
  6847. William H. Press, Saul A. Teukolsky, William T. Vetterling, and Brian P.
  6848. Flannery, _Numerical Recipes in C_, Second Edition, Cambridge University
  6849. Press, 1992, ISBN 0-521-43108-5.
  6850.  
  6851. Dale Schumacher, Ed., _Software Solutions in C_, AP Professional, 1994,
  6852. ISBN 0-12-632360-7.
  6853.  
  6854. Robert Sedgewick, _Algorithms in C_, Addison-Wesley, 1990,
  6855. ISBN 0-201-51425-7.  (A new edition is being prepared;
  6856. the first half is ISBN 0-201-31452-5.)
  6857.  
  6858. Charles Simonyi and Martin Heller, "The Hungarian Revolution," _Byte_,
  6859. August, 1991, pp.131-138.
  6860.  
  6861. David Straker, _C Style: Standards and Guidelines_, Prentice Hall,
  6862. ISBN 0-13-116898-3.
  6863.  
  6864. Steve Summit, _C Programming FAQs: Frequently Asked Questions_, Addison-
  6865. Wesley, 1995, ISBN 0-201-84519-9.  [The book version of this FAQ list;
  6866. see also http://www.eskimo.com/~scs/C-faq/book/Errata.html .]
  6867.  
  6868. Sun Wu and Udi Manber, "AGREP -- A Fast Approximate Pattern-Matching
  6869. Tool," USENIX Conference Proceedings, Winter, 1992, pp. 153-162.
  6870.  
  6871. There is another bibliography in the revised Indian Hill style guide
  6872. (see question 17.9).  See also question 18.10.
  6873.  
  6874.  
  6875. Acknowledgements
  6876.  
  6877. Thanks to Jamshid Afshar, Lauri Alanko, David Anderson, Tanner Andrews,
  6878. Sudheer Apte, Joseph Arceneaux, Randall Atkinson, Rick Beem, Peter
  6879. Bennett, Wayne Berke, Dan Bernstein, Tanmoy Bhattacharya, John Bickers,
  6880. Gary Blaine, Yuan Bo, Mark J. Bobak, Dave Boutcher, Alan Bowler, Michael
  6881. Bresnahan, Walter Briscoe, Vincent Broman, Robert T. Brown, Stan Brown,
  6882. John R. Buchan, Joe Buehler, Kimberley Burchett, Gordon Burditt, Scott
  6883. Burkett, Burkhard Burow, Conor P. Cahill, D'Arcy J.M. Cain, Christopher
  6884. Calabrese, Ian Cargill, Vinit Carpenter, Paul Carter, Mike Chambers,
  6885. Billy Chambless, C. Ron Charlton, Franklin Chen, Jonathan Chen, Raymond
  6886. Chen, Richard Cheung, Avinash Chopde, Steve Clamage, Ken Corbin, Dann
  6887. Corbit, Ian Cottam, Russ Cox, Jonathan Coxhead, Lee Crawford, Nick
  6888. Cropper, Steve Dahmer, Andrew Daviel, James Davies, John E. Davis, Ken
  6889. Delong, Norm Diamond, Bob Dinse, Jeff Dunlop, Ray Dunn, Stephen M. Dunn,
  6890. Michael J. Eager, Scott Ehrlich, Arno Eigenwillig, Yoav Eilat, Dave
  6891. Eisen, Joe English, Bjorn Engsig, David Evans, Clive D.W. Feather,
  6892. Dominic Feeley, Simao Ferraz, Chris Flatters, Rod Flores, Alexander
  6893. Forst, Steve Fosdick, Jeff Francis, Ken Fuchs, Tom Gambill, Dave
  6894. Gillespie, Samuel Goldstein, Tim Goodwin, Alasdair Grant, Ron Guilmette,
  6895. Doug Gwyn, Michael Hafner, Darrel Hankerson, Tony Hansen, Douglas
  6896. Wilhelm Harder, Elliotte Rusty Harold, Joe Harrington, Des Herriott,
  6897. Guy Harris, John Hascall, Ger Hobbelt, Jos Horsmeier, Syed Zaeem Hosain,
  6898. Blair Houghton, James C. Hu, Chin Huang, David Hurt, Einar Indridason,
  6899. Vladimir Ivanovic, Jon Jagger, Ke Jin, Kirk Johnson, Larry Jones, Arjan
  6900. Kenter, Bhaktha Keshavachar, James Kew, Darrell Kindred, Lawrence Kirby,
  6901. Kin-ichi Kitano, Peter Klausler, John Kleinjans, Andrew Koenig, Tom
  6902. Koenig, Adam Kolawa, Jukka Korpela, Ajoy Krishnan T, Jon Krom, Markus
  6903. Kuhn, Deepak Kulkarni, Oliver Laumann, John Lauro, Felix Lee, Mike Lee,
  6904. Timothy J. Lee, Tony Lee, Marty Leisner, Dave Lewis; Don Libes, Brian
  6905. Liedtke, Philip Lijnzaad, Keith Lindsay, Yen-Wei Liu, Paul Long,
  6906. Christopher Lott, Tim Love, Tim McDaniel, J. Scott McKellar, Kevin
  6907. McMahon, Stuart MacMartin, John R. MacMillan, Robert S. Maier, Andrew
  6908. Main, Bob Makowski, Evan Manning, Barry Margolin, George Marsaglia,
  6909. George Matas, Brad Mears, Wayne Mery, De Mickey, Rich Miller, Roger
  6910. Miller, Bill Mitchell, Mark Moraes, Darren Morby, Bernhard Muenzer,
  6911. David Murphy, Walter Murray, Ralf Muschall, Ken Nakata, Todd Nathan,
  6912. Taed Nelson, Landon Curt Noll, Tim Norman, Paul Nulsen, David O'Brien,
  6913. Richard A. O'Keefe, Adam Kolawa, Keith Edward O'hara, James Ojaste, Max
  6914. Okumoto, Hans Olsson, Bob Peck, Andrew Phillips, Christopher Phillips,
  6915. Francois Pinard, Nick Pitfield, Wayne Pollock, Polver@aol.com, Dan Pop,
  6916. Claudio Potenza, Lutz Prechelt, Lynn Pye, Kevin D. Quitt, Pat Rankin,
  6917. Arjun Ray, Eric S. Raymond, Peter W. Richards, James Robinson, Eric
  6918. Roode, Manfred Rosenboom, J. M. Rosenstock, Rick Rowe, Erkki Ruohtula,
  6919. John Rushford, Kadda Sahnine, Tomohiko Sakamoto, Matthew Saltzman, Rich
  6920. Salz, Chip Salzenberg, Matthew Sams, Paul Sand, DaviD W. Sanderson,
  6921. Frank Sandy, Christopher Sawtell, Jonas Schlein, Paul Schlyter, Doug
  6922. Schmidt, Rene Schmit, Russell Schulz, Dean Schulze, Jens Schweikhardt,
  6923. Chris Sears, Peter Seebach, Patricia Shanahan, Aaron Sherman, Raymond
  6924. Shwake, Nathan Sidwell, Peter da Silva, Joshua Simons, Ross Smith, Henri
  6925. Socha, Leslie J. Somos, Henry Spencer, David Spuler, Frederic Stark,
  6926. James Stern, Zalman Stern, Michael Sternberg, Geoff Stevens, Alan
  6927. Stokes, Bob Stout, Dan Stubbs, Steve Sullivan, Melanie Summit, Erik
  6928. Talvola, Dave Taylor, Clarke Thatcher, Wayne Throop, Chris Torek, Steve
  6929. Traugott, Nikos Triantafillis, Ilya Tsindlekht, Andrew Tucker, Goran
  6930. Uddeborg, Rodrigo Vanegas, Jim Van Zandt, Wietse Venema, Tom Verhoeff,
  6931. Ed Vielmetti, Larry Virden, Chris Volpe, Mark Warren, Alan Watson, Kurt
  6932. Watzka, Larry Weiss, Martin Weitzel, Howard West, Tom White, Freek
  6933. Wiedijk, Tim Wilson, Dik T. Winter, Lars Wirzenius, Dave Wolverton,
  6934. Mitch Wright, Conway Yee, Ozan S. Yigit, and Zhuo Zang, who have
  6935. contributed, directly or indirectly, to this article.  Thanks to the
  6936. reviewers of the book-length version: Mark Brader, Vinit Carpenter,
  6937. Stephen Clamage, Jutta Degener, Doug Gwyn, Karl Heuer, and Joseph Kent.
  6938. Thanks to Debbie Lafferty and Tom Stone at Addison-Wesley for
  6939. encouragement, and permission to cross-pollinate this list with new text
  6940. from the book.  Special thanks to Karl Heuer, Jutta Degener, and
  6941. particularly to Mark Brader, who (to borrow a line from Steve Johnson)
  6942. have goaded me beyond my inclination, and occasionally beyond my
  6943. endurance, in relentless pursuit of a better FAQ list.
  6944.  
  6945.                         Steve Summit
  6946.                         scs@eskimo.com
  6947.  
  6948.  
  6949. This article is Copyright 1990-1999 by Steve Summit.
  6950. Content from the book _C Programming FAQs: Frequently Asked Questions_
  6951. is made available here by permission of the author and the publisher as
  6952. a service to the community.  It is intended to complement the use of the
  6953. published text and is protected by international copyright laws.  The
  6954. content is made available here and may be accessed freely for personal
  6955. use but may not be republished without permission.
  6956. With the exception of the examples by other, cited authors (i.e. in
  6957. questions 20.31 and 20.35) the C code in this article is public domain
  6958. and may be used without restriction.
  6959.