home *** CD-ROM | disk | FTP | other *** search
/ Internet Info 1997 December / Internet_Info_CD-ROM_Walnut_Creek_December_1997.iso / faqs / comp / answers / C-faq / faq < prev    next >
Encoding:
Internet Message Format  |  1997-10-02  |  259.6 KB

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