home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / c / 13052 < prev    next >
Encoding:
Text File  |  1992-08-31  |  101.4 KB  |  2,674 lines

  1. Xref: sparky comp.lang.c:13052 news.answers:2668
  2. Newsgroups: comp.lang.c,news.answers
  3. Path: sparky!uunet!haven.umd.edu!darwin.sura.net!gatech!bloom-beacon!bloom-picayune.mit.edu!adam.mit.edu!scs
  4. From: scs@adam.mit.edu (Steve Summit)
  5. Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
  6. Message-ID: <1992Sep1.040213.8937@athena.mit.edu>
  7. Followup-To: poster
  8. Sender: news@athena.mit.edu (News system)
  9. Supersedes: <1992Aug2.041414.15818@athena.mit.edu>
  10. Nntp-Posting-Host: adam.mit.edu
  11. Reply-To: scs@adam.mit.edu
  12. X-Archive-Name: C-faq/faq
  13. Organization: none, at the moment
  14. Date: Tue, 1 Sep 1992 04:02:13 GMT
  15. X-Last-Modified: May 30, 1992
  16. Approved: news-answers-request@MIT.Edu
  17. Expires: Sat, 3 Oct 1992 00:00:00 GMT
  18. Lines: 2654
  19.  
  20. Archive-name: C-faq/faq
  21.  
  22. [Last modified May 30, 1992 by scs.]
  23.  
  24. Certain topics come up again and again on this newsgroup.  They are good
  25. questions, and the answers may not be immediately obvious, but each time
  26. they recur, much net bandwidth and reader time is wasted on repetitive
  27. responses, and on tedious corrections to the incorrect answers which are
  28. inevitably posted.
  29.  
  30. This article, which is posted monthly, attempts to answer these common
  31. questions definitively and succinctly, so that net discussion can move
  32. on to more constructive topics without continual regression to first
  33. principles.
  34.  
  35. No mere newsgroup article can substitute for thoughtful perusal of a
  36. full-length tutorial or language reference manual.  Anyone interested
  37. enough in C to be following this newsgroup should also be interested
  38. enough to read and study one or more such manuals, preferably several
  39. times.  Some vendors' compiler manuals are unfortunately inadequate; a
  40. few even perpetuate some of the myths which this article attempts to
  41. refute.  Several noteworthy books on C are listed in this article's
  42. bibliography.  Many of the questions and answers are cross-referenced to
  43. these books, for further study by the interested and dedicated reader
  44. (but beware of ANSI vs. ISO C Standard section numbers; see question
  45. 4.1).
  46.  
  47. If you have a question about C which is not answered in this article,
  48. first try to answer it by checking a few of the referenced books, or by
  49. asking knowledgeable colleagues, before posing your question to the net
  50. at large.  There are many people on the net who are happy to answer
  51. questions, but the volume of repetitive answers posted to one question,
  52. as well as the growing number of questions as the net attracts more
  53. readers, can become oppressive.  If you have questions or comments
  54. prompted by this article, please reply by mail rather than following up
  55. -- this article is meant to decrease net traffic, not increase it.
  56.  
  57. Besides listing frequently-asked questions, this article also summarizes
  58. frequently-posted answers.  Even if you know all the answers, it's worth
  59. skimming through this list once in a while, so that when you see one of
  60. its questions unwittingly posted, you won't have to waste time
  61. answering.
  62.  
  63. This article is always being improved.  Your input is welcomed.  Send
  64. your comments to scs@adam.mit.edu, scs%adam.mit.edu@mit.edu, and/or
  65. mit-eddie!adam.mit.edu!scs; this article's From: line may be unusable.
  66.  
  67. The questions answered here are divided into several categories:
  68.  
  69.      1. Null Pointers
  70.      2. Arrays and Pointers
  71.      3. Expressions
  72.      4. ANSI C
  73.      5. C Preprocessor
  74.      6. Variable-Length Argument Lists
  75.      7. Lint
  76.      8. Memory Allocation
  77.      9. Structures
  78.     10. Declarations
  79.     11. Boolean Expressions and Variables
  80.     12. System Dependencies
  81.     13. Stdio
  82.     14. Library Subroutines
  83.     15. Style
  84.     16. Miscellaneous (Fortran to C converters, YACC grammars, etc.)
  85.  
  86. Herewith, some frequently-asked questions and their answers:
  87.  
  88.  
  89. Section 1. Null Pointers
  90.  
  91. 1.1:    What is this infamous null pointer, anyway?
  92.  
  93. A:    The language definition states that for each pointer type, there
  94.     is a special value -- the "null pointer" -- which is
  95.     distinguishable from all other pointer values and which is not
  96.     the address of any object.  That is, the address-of operator &
  97.     will never yield a null pointer, nor will a successful call to
  98.     malloc.  (malloc returns a null pointer when it fails, and this
  99.     is a typical use of null pointers: as a "special" pointer value
  100.     with some other meaning, usually "not allocated" or "not
  101.     pointing anywhere yet.")
  102.  
  103.     A null pointer is conceptually different from an uninitialized
  104.     pointer.  A null pointer is known not to point to any object; an
  105.     uninitialized pointer might point anywhere.  See also questions
  106.     8.1, 8.9, and 16.1.
  107.  
  108.     As mentioned in the definition above, there is a null pointer
  109.     for each pointer type, and the internal values of null pointers
  110.     for different types may be different.  Although programmers need
  111.     not know the internal values, the compiler must always be
  112.     informed which type of null pointer is required, so it can make
  113.     the distinction if necessary (see below).
  114.  
  115.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  116.     Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38.
  117.  
  118. 1.2:    How do I "get" a null pointer in my programs?
  119.  
  120. A:    According to the language definition, a constant 0 in a pointer
  121.     context is converted into a null pointer at compile time.  That
  122.     is, in an initialization, assignment, or comparison when one
  123.     side is a variable or expression of pointer type, the compiler
  124.     can tell that a constant 0 on the other side requests a null
  125.     pointer, and generate the correctly-typed null pointer value.
  126.     Therefore, the following fragments are perfectly legal:
  127.  
  128.         char *p = 0;
  129.         if(p != 0)
  130.  
  131.     However, an argument being passed to a function is not
  132.     necessarily recognizable as a pointer context, and the compiler
  133.     may not be able to tell that an unadorned 0 "means" a null
  134.     pointer.  For instance, the Unix system call "execl" takes a
  135.     variable-length, null-pointer-terminated list of character
  136.     pointer arguments.  To generate a null pointer in a function
  137.     call context, an explicit cast is typically required:
  138.  
  139.         execl("/bin/sh", "sh", "-c", "ls", (char *)0);
  140.  
  141.     If the (char *) cast were omitted, the compiler would not know
  142.     to pass a null pointer, and would pass an integer 0 instead.
  143.     (Note that many Unix manuals get this example wrong.)
  144.  
  145.     When function prototypes are in scope, argument passing becomes
  146.     an "assignment context," and most casts may safely be omitted,
  147.     since the prototype tells the compiler that a pointer is
  148.     required, and of which type, enabling it to correctly convert
  149.     unadorned 0's.  Function prototypes cannot provide the types for
  150.     variable arguments in variable-length argument lists, however,
  151.     so explicit casts are still required for those arguments.  It is
  152.     safest always to cast null pointer function arguments, to guard
  153.     against varargs functions or those without prototypes, to allow
  154.     interim use of non-ANSI compilers, and to demonstrate that you
  155.     know what you are doing.  (Incidentally, it's also a simpler
  156.     rule to remember.)
  157.  
  158.     Summary:
  159.  
  160.         Unadorned 0 okay:    Explicit cast required:
  161.  
  162.         initialization        function call,
  163.                     no prototype in scope
  164.         assignment
  165.                     variable argument in
  166.         comparison        varargs function call
  167.  
  168.         function call,
  169.         prototype in scope,
  170.         fixed argument
  171.  
  172.     References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II
  173.     Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI
  174.     Sec. 3.2.2.3 .
  175.  
  176. 1.3:    What is NULL and how is it #defined?
  177.  
  178. A:    As a matter of style, many people prefer not to have unadorned
  179.     0's scattered throughout their programs.  For this reason, the
  180.     preprocessor macro NULL is #defined (by <stdio.h> or
  181.     <stddef.h>), with value 0 (or (void *)0, about which more
  182.     later).  A programmer who wishes to make explicit the
  183.     distinction between 0 the integer and 0 the null pointer can
  184.     then use NULL whenever a null pointer is required.  This is a
  185.     stylistic convention only; the preprocessor turns NULL back to 0
  186.     which is then recognized by the compiler (in pointer contexts)
  187.     as before.  In particular, a cast may still be necessary before
  188.     NULL (as before 0) in a function call argument.  (The table
  189.     under question 1.2 above applies for NULL as well as 0.)
  190.  
  191.     NULL should _only_ be used for pointers; see question 1.8.
  192.  
  193.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  194.     Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38,
  195.     Rationale Sec. 4.1.5 p. 74.
  196.  
  197. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  198.     bit pattern as the internal representation of a null pointer?
  199.  
  200. A:    Programmers should never need to know the internal
  201.     representation(s) of null pointers, because they are normally
  202.     taken care of by the compiler.  If a machine uses a nonzero bit
  203.     pattern for null pointers, it is the compiler's responsibility
  204.     to generate it when the programmer requests, by writing "0" or
  205.     "NULL," a null pointer.  Therefore, #defining NULL as 0 on a
  206.     machine for which internal null pointers are nonzero is as valid
  207.     as on any other, because the compiler must (and can) still
  208.     generate the machine's correct null pointers in response to
  209.     unadorned 0's seen in pointer contexts.
  210.  
  211. 1.5:    If NULL were defined as follows:
  212.  
  213.         #define NULL (char *)0
  214.  
  215.     wouldn't that make function calls which pass an uncast NULL
  216.     work?
  217.  
  218. A:    Not in general.  The problem is that there are machines which
  219.     use different internal representations for pointers to different
  220.     types of data.  The suggested #definition would make uncast NULL
  221.     arguments to functions expecting pointers to characters to work
  222.     correctly, but pointer arguments to other types would still be
  223.     problematical, and legal constructions such as
  224.  
  225.         FILE *fp = NULL;
  226.  
  227.     could fail.
  228.  
  229.     Nevertheless, ANSI C allows the alternate
  230.  
  231.         #define NULL ((void *)0)
  232.  
  233.     definition for NULL.  Besides helping incorrect programs to work
  234.     (but only on machines with homogeneous pointers, thus
  235.     questionably valid assistance) this definition may catch
  236.     programs which use NULL incorrectly (e.g. when the ASCII  NUL
  237.     character was really intended; see question 1.8).
  238.  
  239. 1.6:    I use the preprocessor macro
  240.  
  241.         #define Nullptr(type) (type *)0
  242.  
  243.     to help me build null pointers of the correct type.
  244.  
  245. A:    This trick, though popular in some circles, does not buy much.
  246.     It is not needed in assignments and comparisons; see question
  247.     1.2.  It does not even save keystrokes.  Its use suggests to the
  248.     reader that the author is shaky on the subject of null pointers,
  249.     and requires the reader to check the #definition of the macro,
  250.     its invocations, and _all_ other pointer usages much more
  251.     carefully.
  252.  
  253. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  254.     null pointers valid?  What if the internal representation for
  255.     null pointers is nonzero?
  256.  
  257. A:    When C requires the boolean value of an expression (in the if,
  258.     while, for, and do statements, and with the &&, ||, !, and ?:
  259.     operators), a false value is produced when the expression
  260.     compares equal to zero, and a true value otherwise.  That is,
  261.     whenever one writes
  262.  
  263.         if(expr)
  264.  
  265.     where "expr" is any expression at all, the compiler essentially
  266.     acts as if it had been written as
  267.  
  268.         if(expr != 0)
  269.  
  270.     Substituting the trivial pointer expression "p" for "expr," we
  271.     have
  272.  
  273.         if(p)    is equivalent to        if(p != 0)
  274.  
  275.     and this is a comparison context, so the compiler can tell that
  276.     the (implicit) 0 is a null pointer, and use the correct value.
  277.     There is no trickery involved here; compilers do work this way,
  278.     and generate identical code for both statements.  The internal
  279.     representation of a pointer does _not_ matter.
  280.  
  281.     The boolean negation operator, !, can be described as follows:
  282.  
  283.         !expr    is essentially equivalent to    expr?0:1
  284.  
  285.     It is left as an exercise for the reader to show that
  286.  
  287.         if(!p)    is equivalent to        if(p == 0)
  288.  
  289.     "Abbreviations" such as if(p), though perfectly legal, are
  290.     considered by some to be bad style.
  291.  
  292.     See also question 11.2.
  293.  
  294.     References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI
  295.     Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and
  296.     3.6.5 .
  297.  
  298. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  299.  
  300. A:    Many programmers believe that "NULL" should be used in all
  301.     pointer contexts, as a reminder that the value is to be thought
  302.     of as a pointer.  Others feel that the confusion surrounding
  303.     "NULL" and "0" is only compounded by hiding "0" behind a
  304.     #definition, and prefer to use unadorned "0" instead.  There is
  305.     no one right answer.  C programmers must understand that "NULL"
  306.     and "0" are interchangeable and that an uncast "0" is perfectly
  307.     acceptable in initialization, assignment, and comparison
  308.     contexts.  Any usage of "NULL" (as opposed to "0") should be
  309.     considered a gentle reminder that a pointer is involved;
  310.     programmers should not depend on it (either for their own
  311.     understanding or the compiler's) for distinguishing pointer 0's
  312.     from integer 0's.
  313.  
  314.     NULL should _not_ be used when another kind of 0 is required,
  315.     even though it might work, because doing so sends the wrong
  316.     stylistic message.  (ANSI allows the #definition of NULL to be
  317.     (void *)0, which will not work in non-pointer contexts.)  In
  318.     particular, do not use NULL when the ASCII null character (NUL)
  319.     is desired.  Provide your own definition
  320.  
  321.         #define NUL '\0'
  322.  
  323.     if you must.
  324.  
  325.     Reference: K&R II Sec. 5.4 p. 102.
  326.  
  327. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  328.     the value of NULL changes, perhaps on a machine with nonzero
  329.     null pointers?
  330.  
  331. A:    No.  Although symbolic constants are often used in place of
  332.     numbers because the numbers might change, this is _not_ the
  333.     reason that NULL is used in place of 0.  Once again, the
  334.     language guarantees that source-code 0's (in pointer contexts)
  335.     generate null pointers.  NULL is used only as a stylistic
  336.     convention.
  337.  
  338. 1.10:    I'm confused.  NULL is guaranteed to be 0, but the null pointer
  339.     is not?
  340.  
  341. A:    When the term "null" or "NULL" is casually used, one of several
  342.     things may be meant:
  343.  
  344.     1.    The conceptual null pointer, the abstract language
  345.         concept defined in question 1.1.  It is implemented
  346.         with...
  347.  
  348.     2.    The internal (or run-time) representation of a null
  349.         pointer, which may or may not be all-bits-0 and which
  350.         may be different for different pointer types.  The
  351.         actual values should be of concern only to compiler
  352.         writers.  Authors of C programs never see them, since
  353.         they use...
  354.  
  355.     3.    The source code syntax for null pointers, which is the
  356.         single character "0".  It is often hidden behind...
  357.  
  358.     4.    The NULL macro, which is #defined to be "0" or
  359.         "(void *)0".  Finally, as red herrings, we have...
  360.  
  361.     5.    The ASCII null character (NUL), which does have all bits
  362.         zero, but has no relation to the null pointer except in
  363.         name.  Since this character terminates strings in C, an
  364.         otherwise empty string may be called...
  365.  
  366.     6.    The "null string," consisting only of the terminating
  367.         '\0'.  This term is best avoided, because it could be
  368.         construed as having something to do with null pointers,
  369.         which brings us full circle...
  370.  
  371.     This article always uses the phrase "null pointer" (in lower
  372.     case) for sense 1, the character "0" for sense 3, and the
  373.     capitalized word "NULL" for sense 4.
  374.  
  375. 1.11:    Why is there so much confusion surrounding null pointers?  Why
  376.     do these questions come up so often?
  377.  
  378. A:    C programmers traditionally like to know more than they need to
  379.     about the underlying machine implementation.  The fact that null
  380.     pointers are represented both in source code, and internally to
  381.     most machines, as zero invites unwarranted assumptions.  The use
  382.     of a preprocessor macro (NULL) suggests that the value might
  383.     change later, or on some weird machine.  The construct
  384.     "if(p == 0)" is easily misread as calling for conversion of p to
  385.     an integral type, rather than 0 to a pointer type, before the
  386.     comparison.  Finally, the distinction between the several uses
  387.     of the term "null" (listed above) is often overlooked.
  388.  
  389.     One good way to wade out of the confusion is to imagine that C
  390.     had a keyword (perhaps "nil", like Pascal) with which null
  391.     pointers were requested.  The compiler could either turn "nil"
  392.     into the correct type of null pointer, when it could determine
  393.     the type from the source code, or complain when it could not.
  394.     Now, in fact, in C the keyword for a null pointer is not "nil"
  395.     but "0", which works almost as well, except that an uncast "0"
  396.     in a non-pointer context generates an integer zero instead of an
  397.     error message, and if that uncast 0 was supposed to be a null
  398.     pointer, the code may not work.
  399.  
  400. 1.12:    I'm still confused.  I just can't understand all this null
  401.     pointer stuff.
  402.  
  403. A:    Follow these two simple rules:
  404.  
  405.     1.    When you want to refer to a null pointer in source code,
  406.         use "0" or "NULL".
  407.  
  408.     2.    If the usage of "0" or "NULL" is an argument in a
  409.         function call, cast it to the pointer type expected by
  410.         the function being called.
  411.  
  412.     The rest of the discussion has to do with other people's
  413.     misunderstandings, or with the internal representation of null
  414.     pointers (which you shouldn't need to know), or with ANSI C
  415.     refinements.  Understand questions 1.1, 1.2, and 1.3, and
  416.     consider 1.8 and 1.11, and you'll do fine.
  417.  
  418. 1.13:    Given all the confusion surrounding null pointers, wouldn't it
  419.     be easier simply to require them to be represented internally by
  420.     zeroes?
  421.  
  422. A:    If for no other reason, doing so would be ill-advised because it
  423.     would unnecessarily constrain implementations which would
  424.     otherwise naturally represent null pointers by special, nonzero
  425.     bit patterns, particularly when those values would trigger
  426.     automatic hardware traps for invalid accesses.
  427.  
  428.     Besides, what would this requirement really accomplish?  Proper
  429.     understanding of null pointers does not require knowledge of the
  430.     internal representation, whether zero or nonzero.  Assuming that
  431.     null pointers are internally zero does not make any code easier
  432.     to write (except for a certain ill-advised usage of calloc; see
  433.     question 8.9).  Known-zero internal pointers would not obviate
  434.     casts in function calls, because the _size_ of the pointer might
  435.     still be different from that of an int.  (If "nil" were used to
  436.     request null pointers rather than "0," as mentioned in question
  437.     1.11, the urge to assume an internal zero representation would
  438.     not even arise.)
  439.  
  440. 1.14:    Seriously, have any actual machines really used nonzero null
  441.     pointers, or different representations for pointers to different
  442.     types?
  443.  
  444. A:    The Prime 50 series used segment 07777, offset 0 for the null
  445.     pointer, at least for PL/I.  Later models used segment 0, offset
  446.     0 for null pointers in C, necessitating new instructions such as
  447.     TCNP (Test C Null Pointer), evidently as a sop to all the extant
  448.     poorly-written C code which made incorrect assumptions.  Older,
  449.     word-addressed Prime machines were also notorious for requiring
  450.     larger byte pointers (char *'s) than word pointers (int *'s).
  451.  
  452.     Some Honeywell-Bull mainframes use the bit pattern 06000 for
  453.     (internal) null pointers.
  454.  
  455.     The Symbolics Lisp Machine, a tagged architecture, does not even
  456.     have conventional numeric pointers; it uses the pair <NIL, 0>
  457.     (basically a nonexistent <object, offset> handle) as a C null
  458.     pointer.
  459.  
  460.     Depending on the "memory model" in use, 80*86 processors (PC's)
  461.     may use 16 bit data pointers and 32 bit function pointers, or
  462.     vice versa.
  463.  
  464.  
  465. Section 2. Arrays and Pointers
  466.  
  467. 2.1:    I had the definition char a[6] in one source file, and in
  468.     another I declared extern char *a.  Why didn't it work?
  469.  
  470. A:    The declaration extern char *a simply does not match the actual
  471.     definition.  The type "pointer-to-type-T" is not the same as
  472.     "array-of-type-T."  Use extern char a[].
  473.  
  474.     References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5.
  475.  
  476. 2.2:    But I heard that char a[] was identical to char *a.
  477.  
  478. A:    Not at all.  (What you heard has to do with formal parameters to
  479.     functions; see question 2.4.)  Arrays are not pointers.  The
  480.     array declaration "char a[6];" requests that space for six
  481.     characters be set aside, to be known by the name "a."  That is,
  482.     there is a location named "a" at which six characters can sit.
  483.     The pointer declaration "char *p;" on the other hand, requests a
  484.     place which holds a pointer.  The pointer is to be known by the
  485.     name "p," and can point to any char (or contiguous array of
  486.     chars) anywhere.
  487.  
  488.     As usual, a picture is worth a thousand words.  The statements
  489.  
  490.         char a[] = "hello";
  491.         char *p = "world";
  492.  
  493.     would result in data structures which could be represented like
  494.     this:
  495.  
  496.            +---+---+---+---+---+---+
  497.         a: | h | e | l | l | o |\0 |
  498.            +---+---+---+---+---+---+
  499.  
  500.            +-----+     +---+---+---+---+---+---+
  501.         p: |  *======> | w | o | r | l | d |\0 |
  502.            +-----+     +---+---+---+---+---+---+
  503.  
  504.     It is important to remember that a reference like x[3] generates
  505.     different code depending on whether x is an array or a pointer.
  506.     Given the declarations above, when the compiler sees the
  507.     expression a[3], it emits code to start at the location "a,"
  508.     move three past it, and fetch the character there.  When it sees
  509.     the expression p[3], it emits code to start at the location "p,"
  510.     fetch the pointer value there, add three to the pointer, and
  511.     finally fetch the character pointed to.  In the example above,
  512.     both a[3] and p[3] happen to be the character 'l', but the
  513.     compiler gets there differently.  (See also question 16.11.)
  514.  
  515. 2.3:    So what is meant by the "equivalence of pointers and arrays" in
  516.     C?
  517.  
  518. A:    Much of the confusion surrounding pointers in C can be traced to
  519.     a misunderstanding of this statement.  Saying that arrays and
  520.     pointers are "equivalent" does not by any means imply that they
  521.     are interchangeable.
  522.  
  523.     "Equivalence" refers to the following key definition:
  524.  
  525.         An lvalue of type array-of-T which appears in an
  526.         expression decays (with three exceptions) into a
  527.         pointer to its first element; the type of the
  528.         resultant pointer is pointer-to-T.
  529.  
  530.     (The exceptions are when the array is the operand of a sizeof()
  531.     or & operator, or is a literal string initializer for a
  532.     character array.)
  533.  
  534.     As a consequence of this definition, there is not really any
  535.     difference in the behavior of the "array subscripting" operator
  536.     [] as it applies to arrays and pointers.  In an expression of
  537.     the form a[i], the array reference "a" decays into a pointer,
  538.     following the rule above, and is then subscripted exactly as
  539.     would be a pointer variable in the expression p[i].  In either
  540.     case, the expression x[i] (where x is an array or a pointer) is,
  541.     by definition, exactly equivalent to *((x)+(i)).
  542.  
  543.     References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S
  544.     Sec. 5.4.1 p. 93; ANSI Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6 .
  545.  
  546. 2.4:    Then why are array and pointer declarations interchangeable as
  547.     function formal parameters?
  548.  
  549. A:    Since arrays decay immediately into pointers, an array is never
  550.     actually passed to a function.  Therefore, any parameter
  551.     declarations which "look like" arrays, e.g.
  552.  
  553.         f(a)
  554.         char a[];
  555.  
  556.     are treated by the compiler as if they were pointers, since that
  557.     is what the function will receive if an array is passed:
  558.  
  559.         f(a)
  560.         char *a;
  561.  
  562.     This conversion holds only within function formal parameter
  563.     declarations, nowhere else.  If this conversion bothers you,
  564.     avoid it; many people have concluded that the confusion it
  565.     causes outweighs the small advantage of having the declaration
  566.     "look like" the call and/or the uses within the function.
  567.  
  568.     References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II
  569.     Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S
  570.     Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3
  571.     pp. 33-4.
  572.  
  573. 2.5:    Why doesn't sizeof() properly report the size of an array that's
  574.     a parameter to a subroutine?
  575.  
  576. A:    sizeof() reports the size of the pointer parameter which the
  577.     subroutine really receives (see question 2.4).
  578.  
  579. 2.6:    Someone explained to me that arrays were really just constant
  580.     pointers.
  581.  
  582. A:    This is a bit of an oversimplification.  An array name is
  583.     "constant" in that it cannot be assigned to, but an array is
  584.     _not_ a pointer, as the discussion and pictures in question 2.2
  585.     should make clear.
  586.  
  587. 2.7:    I came across some "joke" code containing the "expression"
  588.     5["abcdef"] .  How can this be legal C?
  589.  
  590. A:    Yes, Virginia, array subscripting is commutative in C.  This
  591.     curious fact follows from the pointer definition of array
  592.     subscripting, namely that a[e] is exactly equivalent to
  593.     *((a)+(e)), for _any_ expression e and primary expression a, as
  594.     long as one of them is a pointer expression and one is integral.
  595.     This unsuspected commutativity is often mentioned in C texts as
  596.     if it were something to be proud of, but it finds no useful
  597.     application outside of the Obfuscated C Contest (see question
  598.     16.7).
  599.  
  600.     References: ANSI Rationale Sec. 3.3.2.1 p. 41.
  601.  
  602. 2.8:    My compiler complained when I passed a two-dimensional array to
  603.     a routine expecting a pointer to a pointer.
  604.  
  605. A:    The rule by which arrays decay into pointers is not applied
  606.     recursively.  An array of arrays (i.e. a two-dimensional array
  607.     in C) decays into a pointer to an array, not a pointer to a
  608.     pointer.  Pointers to arrays can be confusing, and must be
  609.     treated carefully.  (The confusion is heightened by the
  610.     existence of incorrect compilers, including some versions of pcc
  611.     and pcc-derived lint's, which improperly accept assignments of
  612.     multi-dimensional arrays to multi-level pointers.)  If you are
  613.     passing a two-dimensional array to a function:
  614.  
  615.         int array[YSIZE][XSIZE];
  616.         f(array);
  617.  
  618.     the function's declaration should match:
  619.  
  620.         f(int a[][XSIZE]) {...}
  621.     or
  622.         f(int (*ap)[XSIZE]) {...}     /* ap is a pointer to an array */
  623.  
  624.     In the first declaration, the compiler performs the usual
  625.     implicit parameter rewriting of "array of array" to "pointer to
  626.     array;" in the second form the pointer declaration is explicit.
  627.     Since the called function does not allocate space for the array,
  628.     it does not need to know the overall size, so the number of
  629.     "rows," YSIZE, can be omitted.  The "shape" of the array is
  630.     still important, so the "column" dimension XSIZE (and, for 3- or
  631.     more dimensional arrays, the intervening ones) must be included.
  632.  
  633.     If a function is already declared as accepting a pointer to a
  634.     pointer, it is probably incorrect to pass a two-dimensional
  635.     array directly to it.
  636.  
  637.     References: K&R I Sec. 5.10 p. 110; K&R II Sec. 5.9 p. 113.
  638.  
  639. 2.9:    How do I declare a pointer to an array?
  640.  
  641. A:    Usually, you don't want to.  Consider using a pointer to one of
  642.     the array's elements instead.  Arrays of type T decay into
  643.     pointers to type T (see question 2.3), which is convenient;
  644.     subscripting or incrementing the resultant pointer accesses the
  645.     individual members of the array.  True pointers to arrays, when
  646.     subscripted or incremented, step over entire arrays, and are
  647.     generally only useful when operating on arrays of arrays, if at
  648.     all.  (See question 2.8 above.)  When people speak casually of a
  649.     pointer to an array, they usually mean a pointer to its first
  650.     element.
  651.  
  652.     If you really need to declare a pointer to an entire array, use
  653.     something like "int (*ap)[N];" where N is the size of the array.
  654.     (See also question 10.3.)  If the size of the array is unknown,
  655.     N can be omitted, but the resulting type, "pointer to array of
  656.     unknown size," is useless.
  657.  
  658. 2.10:    How can I dynamically allocate a multidimensional array?
  659.  
  660. A:    It is usually best to allocate an array of pointers, and then
  661.     initialize each pointer to a dynamically-allocated "row."  The
  662.     resulting "ragged" array can save space, although it is not
  663.     necessarily contiguous in memory as a real array would be.  Here
  664.     is a two-dimensional example:
  665.  
  666.         int **array = (int **)malloc(nrows * sizeof(int *));
  667.         for(i = 0; i < nrows; i++)
  668.             array[i] = (int *)malloc(ncolumns * sizeof(int));
  669.  
  670.     (In "real" code, of course, malloc would be declared correctly,
  671.     and each return value checked.)
  672.  
  673.     You can keep the array's contents contiguous, while making later
  674.     reallocation of individual rows difficult, with a bit of
  675.     explicit pointer arithmetic:
  676.  
  677.         int **array = (int **)malloc(nrows * sizeof(int *));
  678.         array[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  679.         for(i = 1; i < nrows; i++)
  680.             array[i] = array[0] + i * ncolumns;
  681.  
  682.     In either case, the elements of the dynamic array can be
  683.     accessed with normal-looking array subscripts: array[i][j].
  684.  
  685.     If the double indirection implied by the above schemes is for
  686.     some reason unacceptable, you can simulate a two-dimensional
  687.     array with a single, dynamically-allocated one-dimensional
  688.     array:
  689.  
  690.         int *array = (int *)malloc(nrows * ncolumns * sizeof(int));
  691.  
  692.     However, you must now perform subscript calculations manually,
  693.     accessing the i,jth element with array[i * ncolumns + j].  (A
  694.     macro can hide the explicit calculation, but invoking it then
  695.     requires parentheses and commas which don't look exactly like
  696.     multidimensional array subscripts.)
  697.  
  698. 2.11:    Here's a neat trick: if I write
  699.  
  700.         int realarray[10];
  701.         int *array = &realarray[-1];
  702.  
  703.     I can treat "array" as if it were a 1-based array.
  704.  
  705. A:    This technique, though attractive, is not strictly conforming to
  706.     the C standards (in spite of its appearance in Numerical Recipes
  707.     in C).  Pointer arithmetic is defined only as long as the
  708.     pointer points within the same allocated block of memory, or to
  709.     the imaginary "terminating" element one past it; otherwise, the
  710.     behavior is undefined, _even if the pointer is not
  711.     dereferenced_.  The code above could fail if, while subtracting
  712.     the offset, an illegal address were generated (perhaps because
  713.     the address tried to "wrap around" past the beginning of some
  714.     memory segment).
  715.  
  716.     References: K&R II Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3,
  717.     Sec. A7.7 pp. 205-6; ANSI Rationale Sec. 3.2.2.3 p. 38.
  718.  
  719. 2.12:    I have a char * pointer that happens to point to some ints, and
  720.     I want to step it over them.  Why doesn't
  721.  
  722.         ((int *)p)++;
  723.  
  724.     work?
  725.  
  726. A:    In C, a cast operator does not mean "pretend these bits have a
  727.     different type, and treat them accordingly;" it is a conversion
  728.     operator, and by definition it yields an rvalue, which cannot be
  729.     assigned to, or incremented with ++.  (It is an anomaly in pcc-
  730.     derived compilers, and an extension in gcc, that expressions
  731.     such as the above are ever accepted.)  Say what you mean: use
  732.  
  733.         p = (char *)((int *)p + 1);
  734.  
  735.     References: ANSI Sec. 3.3.4, Rationale Sec. 3.3.2.4 p. 43.
  736.  
  737.  
  738. Section 3. Expressions
  739.  
  740. 3.1:    Under my compiler, the code
  741.  
  742.         int i = 7;
  743.         printf("%d\n", i++ * i++);
  744.  
  745.     prints 49.  Regardless of the order of evaluation, shouldn't it
  746.     print 56?
  747.  
  748. A:    Although the postincrement and postdecrement operators ++ and --
  749.     perform the operations after yielding the former value, the
  750.     implication of "after" is often misunderstood.  It is _not_
  751.     guaranteed that the operation is performed immediately after
  752.     giving up the previous value and before any other part of the
  753.     expression is evaluated.  It is merely guaranteed that the
  754.     update will be performed sometime before the expression is
  755.     considered "finished" (before the next "sequence point," in ANSI
  756.     C's terminology).  In the example, the compiler chose to
  757.     multiply the previous value by itself and to perform both
  758.     increments afterwards.
  759.  
  760.     The behavior of code which contains multiple, ambiguous side
  761.     effects has always been undefined.  Don't even try to find out
  762.     how your compiler implements such things (contrary to the ill-
  763.     advised exercises in many C textbooks); as K&R wisely point out,
  764.     "if you don't know _how_ they are done on various machines, that
  765.     innocence may help to protect you."
  766.  
  767.     References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI
  768.     Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1.
  769.     (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.)
  770.  
  771. 3.2:    But what about the &&, ||, and comma operators?
  772.     I see code like "if((c = getchar()) == EOF || c == '\n')" ...
  773.  
  774. A:    There is a special exception for those operators, (as well as
  775.     ?: ); each of them does imply a sequence point (i.e. left-to-
  776.     right evaluation is guaranteed).  Any book on C should make this
  777.     clear.
  778.  
  779.     References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1;
  780.     K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI
  781.     Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55,
  782.     CT&P Sec. 3.7 pp. 46-7.
  783.  
  784. 3.3:    If I'm not using the value of the expression, should I use i++
  785.     or ++i to increment a variable?
  786.  
  787. A:    Since the two forms differ only in the value yielded, they are
  788.     entirely equivalent when only their side effect is needed.  Some
  789.     people will tell you that in the old days one form was preferred
  790.     over the other because it utilized a PDP-11 autoincrement
  791.     addressing mode, but those people are confused.
  792.  
  793. 3.4:    Why doesn't the code
  794.  
  795.         int a = 1000, b = 1000;
  796.         long int c = a * b;
  797.  
  798.     work?
  799.  
  800. A:    Under C's integral promotion rules, the multiplication is
  801.     carried out using integer arithmetic, and the result overflows
  802.     and/or is truncated before being assigned to the long int left-
  803.     hand-side.  Use an explicit cast to force long arithmetic:
  804.  
  805.         long int c = (long int)a * b;
  806.  
  807.  
  808. Section 4. ANSI C
  809.  
  810. 4.1:    What is the "ANSI C Standard?"
  811.  
  812. A:    In 1983, the American National Standards Institute commissioned
  813.     a committee, X3J11, to standardize the C language.  After a
  814.     long, arduous process, including several widespread public
  815.     reviews, the committee's work was finally ratified as an
  816.     American National Standard, X3.159-1989, on December 14, 1989,
  817.     and published in the spring of 1990.  For the most part, ANSI C
  818.     standardizes existing practice, with a few additions from C++
  819.     (most notably function prototypes) and support for multinational
  820.     character sets (including the much-lambasted trigraph
  821.     sequences).  The ANSI C standard also formalizes the C run-time
  822.     library support routines.
  823.  
  824.     The published Standard includes a "Rationale," which explains
  825.     many of its decisions, and discusses a number of subtle points,
  826.     including several of those covered here.  (The Rationale is "not
  827.     part of ANSI Standard X3.159-1989, but is included for
  828.     information only.")
  829.  
  830.     The Standard has been adopted as an international standard,
  831.     ISO/IEC 9899:1990, although the sections are numbered
  832.     differently (briefly, ANSI sections 2 through 4 correspond
  833.     roughly to ISO sections 5 through 7), and the Rationale is
  834.     currently not included.
  835.  
  836. 4.2:    How can I get a copy of the Standard?
  837.  
  838. A:    Copies are available from
  839.  
  840.         American National Standards Institute
  841.         1430 Broadway
  842.         New York, NY  10018  USA
  843.         (+1) 212 642 4900
  844.  
  845.     or
  846.  
  847.         Global Engineering Documents
  848.         2805 McGaw Avenue
  849.         Irvine, CA  92714  USA
  850.         (+1) 714 261 1455
  851.         (800) 854 7179  (U.S. & Canada)
  852.  
  853.     The cost from ANSI is $50.00, plus $6.00 shipping.  Quantity
  854.     discounts are available.  (Note that ANSI derives revenues to
  855.     support its operations from the sale of printed standards, so
  856.     electronic copies are _not_ available.)
  857.  
  858.     The Rationale, by itself, has been printed by Silicon Press,
  859.     ISBN 0-929306-07-4.
  860.  
  861. 4.3:    Does anyone have a tool for converting old-style C programs to
  862.     ANSI C, or for automatically generating prototypes?
  863.  
  864. A:    Two programs, protoize and unprotoize, convert back and forth
  865.     between prototyped and "old style" function definitions and
  866.     declarations.  (These programs do _not_ handle full-blown
  867.     translation between "Classic" C and ANSI C.)  These programs
  868.     exist as patches to the FSF GNU C compiler, gcc.  Look for the
  869.     file protoize-1.39.0.5.Z in pub/gnu at prep.ai.mit.edu
  870.     (18.71.0.38), or at several other FSF archive sites.
  871.  
  872.     The unproto program (/pub/unix/unproto4.shar.Z on
  873.     ftp.win.tue.nl) is a filter which sits between the preprocessor
  874.     and the next compiler pass, converting most of ANSI C to
  875.     traditional C on-the-fly.
  876.  
  877.     Several prototype generators exist, many as modifications to
  878.     lint.  Version 3 of CPROTO was posted to comp.sources.misc in
  879.     March, 1992.  (See also question 16.6.)
  880.  
  881. 4.4:    I'm trying to use the ANSI "stringizing" preprocessing operator
  882.     # to insert the value of a symbolic constant into a message, but
  883.     it keeps stringizing the macro's name rather than its value.
  884.  
  885. A:    You must use something like the following two-step procedure to
  886.     force the macro to be expanded as well as stringized:
  887.  
  888.         #define str(x) #x
  889.         #define xstr(x) str(x)
  890.         #define OP plus
  891.         char *opname = xstr(OP);
  892.  
  893.     This sets opname to "plus" rather than "OP".
  894.  
  895.     An equivalent circumlocution is necessary with the token-pasting
  896.     operator ## when the values (rather than the names) of two
  897.     macros are to be concatenated.
  898.  
  899.     References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example p. 93.
  900.  
  901. 4.5:    What's the difference between "char const *p" and
  902.     "char * const p"?
  903.  
  904. A:    "char const *p" is a pointer to a constant character (you can't
  905.     change the character); "char * const p" is a constant pointer to
  906.     a (variable) character (i.e. you can't change the pointer).
  907.     (Read these "inside out" to understand them.  See question
  908.     10.3.)
  909.  
  910.     References: ANSI Sec. 3.5.4.1 .
  911.  
  912. 4.6:    My ANSI compiler complains about a mismatch when it sees
  913.  
  914.         extern int func(float);
  915.  
  916.         int func(x)
  917.         float x;
  918.         {...
  919.  
  920. A:    You have mixed the new-style prototype declaration
  921.     "extern int func(float);" with the old-style definition
  922.     "int func(x) float x;".  Old C (and ANSI C, in the absence of
  923.     prototypes) silently promotes floats to doubles when passing
  924.     them as arguments, and arranges that doubles being passed are
  925.     coerced back to floats if the formal parameters are declared
  926.     that way.
  927.  
  928.     The problem can be fixed either by using new-style syntax
  929.     consistently in the definition:
  930.  
  931.         int func(float x) { ... }
  932.  
  933.     or by changing the new-style prototype declaration to match the
  934.     old-style definition:
  935.  
  936.         extern int func(double);
  937.  
  938.     (In this case, it would be clearest to change the old-style
  939.     definition to use double as well, as long as the address of that
  940.     parameter is not taken.)
  941.  
  942.     It may also be safer to avoid "narrow" (char, short int, and
  943.     float) function arguments and return types.
  944.  
  945.     References: ANSI Sec. 3.3.2.2 .
  946.  
  947. 4.7:    I'm getting strange syntax errors inside code which I've
  948.     #ifdeffed out.
  949.  
  950. A:    Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  951.     #ifndef must still consist of "valid preprocessing tokens."
  952.     This means that there must be no unterminated comments or quotes
  953.     (note particularly that an apostrophe within a contracted word
  954.     could look like the beginning of a character constant), and no
  955.     newlines inside quotes.  Therefore, natural-language comments
  956.     and pseudocode should always be written between the "official"
  957.     comment delimiters /* and */.  (But see also question 16.8.)
  958.  
  959.     References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37.
  960.  
  961. 4.8:    Can I declare main as void, to shut off these annoying "main
  962.     returns no value" messages?  (I'm calling exit(), so main
  963.     doesn't return.)
  964.  
  965. A:    No.  main must be declared as returning an int, and as taking
  966.     either zero or two arguments (of the appropriate type).  If
  967.     you're calling exit() but still getting warnings, you'll have to
  968.     insert a redundant return statement (or use some kind of
  969.     "notreached" directive, if available).
  970.  
  971.     References: ANSI Sec. 2.1.2.2.1 pp. 7-8.
  972.  
  973. 4.9:    Why does the ANSI Standard not guarantee more than six monocase
  974.     characters of external identifier significance?
  975.  
  976. A:    The problem is older linkers which are neither under the control
  977.     of the ANSI standard nor the C compiler developers on the
  978.     systems which have them.  The limitation is only that
  979.     identifiers be _significant_ in the first six characters, not
  980.     that they be restricted to six characters in length.  This
  981.     limitation is annoying, but certainly not unbearable, and is
  982.     marked in the Standard as "obsolescent," i.e. a future revision
  983.     will likely relax it.
  984.  
  985.     This concession to current, restrictive linkers really had to be
  986.     made, no matter how vehemently some people oppose it.  (The
  987.     Rationale notes that its retention was "most painful.")  If you
  988.     disagree, or have thought of a trick by which a compiler
  989.     burdened with a restrictive linker could present the C
  990.     programmer with the appearance of more significance in external
  991.     identifiers, read the excellently-worded section 3.1.2 in the
  992.     X3.159 Rationale (see question 4.1), which discusses several
  993.     such schemes and explains why they could not be mandated.
  994.  
  995.     References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale
  996.     Sec. 3.1.2 pp. 19-21.
  997.  
  998. 4.10:    What is the difference between memcpy and memmove?
  999.  
  1000. A:    memmove offers guaranteed behavior if the source and destination
  1001.     arguments overlap.  memcpy makes no such guarantee, and may
  1002.     therefore be more efficiently implementable.  When in doubt,
  1003.     it's safer to use memmove.
  1004.  
  1005.     References: ANSI Secs. 4.11.2.1, 4.11.2.2, Rationale
  1006.     Sec. 4.11.2 .
  1007.  
  1008. 4.11:    What are #pragmas and what are they good for?
  1009.  
  1010. A:    The #pragma directive provides a single, well-defined "escape
  1011.     hatch" which can be used for all sorts of implementation-
  1012.     specific controls and extensions: source listing control,
  1013.     structure packing, warning suppression (like the old lint
  1014.     /* NOTREACHED */ comments), etc.
  1015.  
  1016.     References: ANSI Sec. 3.8.6 .
  1017.  
  1018.  
  1019. Section 5. C Preprocessor
  1020.  
  1021. 5.1:    How can I write a generic macro to swap two values?
  1022.  
  1023. A:    There is no good answer to this question.  If the values are
  1024.     integers, a well-known trick using exclusive-OR could perhaps be
  1025.     used, but it will not work for floating-point values or
  1026.     pointers, (and it will not work if the two values are the same
  1027.     variable, and the "obvious" supercompressed implementation for
  1028.     integral types a^=b^=a^=b is, strictly speaking, illegal due to
  1029.     multiple side-effects, and...).  If the macro is intended to be
  1030.     used on values of arbitrary type (the usual goal), it cannot use
  1031.     a temporary, since it does not know what type of temporary it
  1032.     needs, and standard C does not provide a typeof operator.
  1033.  
  1034.     The best all-around solution is probably to forget about using a
  1035.     macro, unless you don't mind passing in the type as a third
  1036.     argument.
  1037.  
  1038. 5.2:    I have some old code that tries to construct identifiers with a
  1039.     macro like
  1040.  
  1041.         #define Paste(a, b) a/**/b
  1042.  
  1043.     but it doesn't work any more.
  1044.  
  1045. A:    That comments disappeared entirely and could therefore be used
  1046.     for token pasting was an undocumented feature of some early
  1047.     preprocessor implementations, notably Reiser's.  ANSI affirms
  1048.     (as did K&R) that comments are replaced with white space.
  1049.     However, since the need for pasting tokens was demonstrated and
  1050.     real, ANSI introduced a well-defined token-pasting operator, ##,
  1051.     which can be used like this:
  1052.  
  1053.         #define Paste(a, b) a##b
  1054.  
  1055.     (See also question 4.4.)
  1056.  
  1057.     Reference: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7.
  1058.  
  1059. 5.3:    What's the best way to write a multi-statement cpp macro?
  1060.  
  1061. A:    The usual goal is to write a macro that can be invoked as if it
  1062.     were a single function-call statement.  This means that the
  1063.     "caller" will be supplying the final semicolon, so the macro
  1064.     body should not.  The macro body cannot be a simple brace-
  1065.     delineated compound statement, because syntax errors would
  1066.     result if it were invoked (apparently as a single statement, but
  1067.     with a resultant extra semicolon) as the if branch of an if/else
  1068.     statement with an explicit else clause.
  1069.  
  1070.     The traditional solution is to use
  1071.  
  1072.         #define Func() do { \
  1073.             /* declarations */ \
  1074.             stmt1; \
  1075.             stmt2; \
  1076.             /* ... */ \
  1077.             } while(0)    /* (no trailing ; ) */
  1078.  
  1079.     When the "caller" appends a semicolon, this expansion becomes a
  1080.     single statement regardless of context.  (An optimizing compiler
  1081.     will remove any "dead" tests or branches on the constant
  1082.     condition 0, although lint may complain.)
  1083.  
  1084.     If all of the statements in the intended macro are simple
  1085.     expressions, with no declarations or loops, another technique is
  1086.     to write a single, parenthesized expression using one or more
  1087.     comma operators.  (See the example under question 5.8 below.
  1088.     This technique also allows a value to be "returned.")
  1089.  
  1090.     Reference: CT&P Sec. 6.3 pp. 82-3.
  1091.  
  1092. 5.4:    Is it acceptable for one header file to #include another?
  1093.  
  1094. A:    There has been considerable debate surrounding this question.
  1095.     Many people believe that "nested #include files" are to be
  1096.     avoided: the prestigious Indian Hill Style Guide disparages
  1097.     them; they can make it harder to find relevant definitions; they
  1098.     can lead to multiple-declaration errors if a file is #included
  1099.     twice; and they make manual Makefile maintenance very difficult.
  1100.     On the other hand, they make it possible to use header files in
  1101.     a modular way (a header file #includes what it needs itself,
  1102.     rather than requiring each #includer to do so, a requirement
  1103.     that can lead to intractable headaches); a tool like grep (or a
  1104.     tags file) makes it easy to find definitions no matter where
  1105.     they are; a popular trick:
  1106.  
  1107.         #ifndef HEADER_FILE_NAME
  1108.         #define HEADER_FILE_NAME
  1109.         ...header file contents...
  1110.         #endif
  1111.  
  1112.     makes a header file "idempotent" so that it can safely be
  1113.     #included multiple times; and automated Makefile maintenance
  1114.     tools (which are a virtual necessity in large projects anyway)
  1115.     handle dependency generation in the face of nested #include
  1116.     files easily.
  1117.  
  1118. 5.5:    Does sizeof() work in preprocessor #if directives?
  1119.  
  1120. A:    No.  Preprocessing happens during an earlier pass of
  1121.     compilation, before type names have been parsed.  Consider using
  1122.     the predefined constants in <limits.h>, or a "configure" script,
  1123.     instead.
  1124.  
  1125.     References: ANSI Sec. 2.1.1.2 pp. 6-7, Sec. 3.8.1 p. 87
  1126.     footnote 83.
  1127.  
  1128. 5.6:    How can I use a preprocessor #if expression to tell if a machine
  1129.     is big-endian or little-endian?
  1130.  
  1131. A:    You probably can't.  (Preprocessor arithmetic uses only long
  1132.     ints, and there is no concept of addressing.)  Are you sure you
  1133.     need to know the machine's endianness explicitly?  Usually it's
  1134.     better to write code which doesn't care.
  1135.  
  1136. 5.7:    I've got this tricky processing I want to do at compile time and
  1137.     I can't figure out a way to get cpp to do it.
  1138.  
  1139. A:    cpp is not intended as a general-purpose preprocessor.  Rather
  1140.     than forcing it to do something inappropriate, consider writing
  1141.     your own little special-purpose preprocessing tool, instead.
  1142.     You can easily get a utility like make(1) to run it for you
  1143.     automatically.
  1144.  
  1145. 5.8:    How can I write a cpp macro which takes a variable number of
  1146.     arguments?
  1147.  
  1148. A:    One popular trick is to define the macro with a single argument,
  1149.     and call it with a double set of parentheses, which appear to
  1150.     the preprocessor to indicate a single argument:
  1151.  
  1152.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  1153.  
  1154.         if(n != 0) DEBUG(("n is %d\n", n));
  1155.  
  1156.     The obvious disadvantage is that the caller must always remember
  1157.     to use the extra parentheses.  (It is often better to use a
  1158.     bona-fide function, which can take a variable number of
  1159.     arguments in a well-defined way.  See questions 6.1 and 6.2
  1160.     below.)
  1161.  
  1162.  
  1163. Section 6. Variable-Length Argument Lists
  1164.  
  1165. 6.1:    How can I write a function that takes a variable number of
  1166.     arguments?
  1167.  
  1168. A:    Use the <stdarg.h> header (or, if you must, the older
  1169.     <varargs.h>).
  1170.  
  1171.     Here is a function which concatenates an arbitrary number of
  1172.     strings into malloc'ed memory:
  1173.  
  1174.         #include <stddef.h>        /* for NULL, size_t */
  1175.         #include <stdarg.h>        /* for va_ stuff */
  1176.         #include <string.h>        /* for strcat et al */
  1177.         #include <stdlib.h>        /* for malloc */
  1178.  
  1179.         char *vstrcat(char *first, ...)
  1180.         {
  1181.             size_t len = 0;
  1182.             char *retbuf;
  1183.             va_list argp;
  1184.             char *p;
  1185.  
  1186.             if(first == NULL)
  1187.                 return NULL;
  1188.  
  1189.             len = strlen(first);
  1190.  
  1191.             va_start(argp, first);
  1192.  
  1193.             while((p = va_arg(argp, char *)) != NULL)
  1194.                 len += strlen(p);
  1195.  
  1196.             va_end(argp);
  1197.  
  1198.             retbuf = malloc(len + 1);    /* +1 for trailing \0 */
  1199.  
  1200.             if(retbuf == NULL)
  1201.                 return NULL;        /* error */
  1202.  
  1203.             (void)strcpy(retbuf, first);
  1204.  
  1205.             va_start(argp, first);
  1206.  
  1207.             while((p = va_arg(argp, char *)) != NULL)
  1208.                 (void)strcat(retbuf, p);
  1209.  
  1210.             va_end(argp);
  1211.  
  1212.             return retbuf;
  1213.         }
  1214.  
  1215.     Usage is something like
  1216.  
  1217.         char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  1218.  
  1219.     Note the cast on the last argument.  (Also note that the caller
  1220.     must free the returned, malloc'ed storage.)
  1221.  
  1222.     Under a pre-ANSI compiler, rewrite the function definition
  1223.     without a prototype ("char *vstrcat(first) char *first; {"),
  1224.     include <stdio.h> rather than <stddef.h>, replace "#include
  1225.     <stdlib.h>" with "extern char *malloc();", and use int instead
  1226.     of size_t.  You may also have to delete the (void) casts, and
  1227.     use the older varargs package instead of stdarg.  See the next
  1228.     question for hints.
  1229.  
  1230.     References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S
  1231.     Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 .
  1232.  
  1233. 6.2:    How can I write a function that takes a format string and a
  1234.     variable number of arguments, like printf, and passes them to
  1235.     printf to do most of the work?
  1236.  
  1237. A:    Use vprintf, vfprintf, or vsprintf.
  1238.  
  1239.     Here is an "error" routine which prints an error message,
  1240.     preceded by the string "error: " and terminated with a newline:
  1241.  
  1242.         #include <stdio.h>
  1243.         #include <stdarg.h>
  1244.  
  1245.         void
  1246.         error(char *fmt, ...)
  1247.         {
  1248.             va_list argp;
  1249.             fprintf(stderr, "error: ");
  1250.             va_start(argp, fmt);
  1251.             vfprintf(stderr, fmt, argp);
  1252.             va_end(argp);
  1253.             fprintf(stderr, "\n");
  1254.         }
  1255.  
  1256.     To use the older <varargs.h> package, instead of <stdarg.h>,
  1257.     change the function header to:
  1258.  
  1259.         void error(va_alist)
  1260.         va_dcl
  1261.         {
  1262.             char *fmt;
  1263.  
  1264.     change the va_start line to
  1265.  
  1266.         va_start(argp);
  1267.  
  1268.     and add the line
  1269.  
  1270.         fmt = va_arg(argp, char *);
  1271.  
  1272.     between the calls to va_start and vfprintf.  (Note that there is
  1273.     no semicolon after va_dcl.)
  1274.  
  1275.     References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S
  1276.     Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .
  1277.  
  1278. 6.3:    How can I discover how many arguments a function was actually
  1279.     called with?
  1280.  
  1281. A:    This information is not available to a portable program.  Some
  1282.     systems provide a nonstandard nargs() function, but its use is
  1283.     questionable, since it typically returns the number of words
  1284.     passed, not the number of arguments.  (Floating point values and
  1285.     structures are usually passed as several words.)
  1286.  
  1287.     Any function which takes a variable number of arguments must be
  1288.     able to determine from the arguments themselves how many of them
  1289.     there are.  printf-like functions do this by looking for
  1290.     formatting specifiers (%d and the like) in the format string
  1291.     (which is why these functions fail badly if the format string
  1292.     does not match the argument list).  Another common technique
  1293.     (useful when the arguments are all of the same type) is to use a
  1294.     sentinel value (often 0, -1, or an appropriately-cast null
  1295.     pointer) at the end of the list (see the execl and vstrcat
  1296.     examples under questions 1.2 and 6.1 above).
  1297.  
  1298. 6.4:    How can I write a function which takes a variable number of
  1299.     arguments and passes them to some other function (which takes a
  1300.     variable number of arguments)?
  1301.  
  1302. A:    In general, you cannot.  You must provide a version of that
  1303.     other function which accepts a va_list pointer, as does vfprintf
  1304.     in the example above.  If the arguments must be passed directly
  1305.     as actual arguments (not indirectly through a va_list pointer)
  1306.     to another function which is itself variadic (for which you do
  1307.     not have the option of creating an alternate, va_list-accepting
  1308.     version) no portable solution is possible.  (The problem can be
  1309.     solved by resorting to machine-specific assembly language.)
  1310.  
  1311.  
  1312. Section 7. Lint
  1313.  
  1314. 7.1:    I just typed in this program, and it's acting strangely.  Can
  1315.     you see anything wrong with it?
  1316.  
  1317. A:    Try running lint first.  Many C compilers are really only half-
  1318.     compilers, electing not to diagnose numerous source code
  1319.     difficulties which would not actively preclude code generation.
  1320.  
  1321. 7.2:    How can I shut off the "warning: possible pointer alignment
  1322.     problem" message lint gives me for each call to malloc?
  1323.  
  1324. A:    The problem is that traditional versions of lint do not know,
  1325.     and cannot be told, that malloc "returns a pointer to space
  1326.     suitably aligned for storage of any type of object."  It is
  1327.     possible to provide a pseudoimplementation of malloc, using a
  1328.     #define inside of #ifdef lint, which effectively shuts this
  1329.     warning off, but a simpleminded #definition will also suppress
  1330.     meaningful messages about truly incorrect invocations.  It may
  1331.     be easier simply to ignore the message, perhaps in an automated
  1332.     way with grep -v.
  1333.  
  1334. 7.3:    Where can I get an ANSI-compatible lint?
  1335.  
  1336. A:    A product called FlexeLint is available (in "shrouded source
  1337.     form," for compilation on 'most any system) from
  1338.  
  1339.         Gimpel Software
  1340.         3207 Hogarth Lane
  1341.         Collegeville, PA  19426  USA
  1342.         (+1) 215 584 4261
  1343.  
  1344.     The System V release 4 lint is ANSI-compatible, and is available
  1345.     separately (bundled with other C tools) from Unix Support Labs
  1346.     (a subsidiary of AT&T), or from System V resellers.
  1347.  
  1348.  
  1349. Section 8. Memory Allocation
  1350.  
  1351. 8.1:    Why doesn't this fragment work?
  1352.  
  1353.         char *answer;
  1354.         printf("Type something:\n");
  1355.         gets(answer);
  1356.         printf("You typed \"%s\"\n", answer);
  1357.  
  1358. A:    The pointer variable "answer," which is handed to the gets
  1359.     function as the location into which the response should be
  1360.     stored, has not been set to point to any valid storage.  That
  1361.     is, we cannot say where the pointer "answer" points.  (Since
  1362.     local variables are not initialized, and typically contain
  1363.     garbage, it is not even guaranteed that "answer" starts out as a
  1364.     null pointer.  See question 16.1.)
  1365.  
  1366.     The simplest way to correct the question-asking program is to
  1367.     use a local array, instead of a pointer, and let the compiler
  1368.     worry about allocation:
  1369.  
  1370.         #include <string.h>
  1371.  
  1372.         char answer[100], *p;
  1373.         printf("Type something:\n");
  1374.         fgets(answer, 100, stdin);
  1375.         if((p = strchr(answer, '\n')) != NULL)
  1376.             *p = '\0';
  1377.         printf("You typed \"%s\"\n", answer);
  1378.  
  1379.     Note that this example also uses fgets instead of gets (always a
  1380.     good idea), so that the size of the array can be specified, so
  1381.     that fgets will not overwrite the end of the array if the user
  1382.     types an overly-long line.  (Unfortunately for this example,
  1383.     fgets does not automatically delete the trailing \n, as gets
  1384.     would.)  It would also be possible to use malloc to allocate the
  1385.     answer buffer, and/or to parameterize its size
  1386.     (#define ANSWERSIZE 100).
  1387.  
  1388. 8.2:    I can't get strcat to work.  I tried
  1389.  
  1390.         char *s1 = "Hello, ";
  1391.         char *s2 = "world!";
  1392.         char *s3 = strcat(s1, s2);
  1393.  
  1394.     but I got strange results.
  1395.  
  1396. A:    Again, the problem is that space for the concatenated result is
  1397.     not properly allocated.  C does not provide an automatically-
  1398.     managed string type.  C compilers only allocate memory for
  1399.     objects explicitly mentioned in the source code (in the case of
  1400.     "strings," this includes character arrays and string literals).
  1401.     The programmer must arrange (explicitly) for sufficient space
  1402.     for the results of run-time operations such as string
  1403.     concatenation, typically by declaring arrays, or by calling
  1404.     malloc.
  1405.  
  1406.     strcat performs no allocation; the second string is appended to
  1407.     the first one, in place.  Therefore, one fix would be to declare
  1408.     the first string as an array with sufficient space:
  1409.  
  1410.         char s1[20] = "Hello, ";
  1411.  
  1412.     Since strcat returns the value of its first argument (s1, in
  1413.     this case), the s3 variable is superfluous.
  1414.  
  1415.     Reference: CT&P Sec. 3.2 p. 32.
  1416.  
  1417. 8.3:    But the man page for strcat says that it takes two char *'s as
  1418.     arguments.  How am I supposed to know to allocate things?
  1419.  
  1420. A:    In general, when using pointers you _always_ have to consider
  1421.     memory allocation, at least to make sure that the compiler is
  1422.     doing it for you.  If a library routine's documentation does not
  1423.     explicitly mention allocation, it is usually the caller's
  1424.     problem.
  1425.  
  1426.     The Synopsis section at the top of a Unix-style man page can be
  1427.     misleading.  The code fragments presented there are closer to
  1428.     the function definition used by the call's implementor than the
  1429.     invocation used by the caller.  In particular, many routines
  1430.     which accept pointers (e.g. to structs or strings), are usually
  1431.     called with the address of some object (a struct, or an array --
  1432.     see questions 2.3 and 2.4.)  Another common example is stat().
  1433.  
  1434. 8.4:    I have a function that returns a string, and it seems to work
  1435.     fine under the debugger, but when it returns to its caller, the
  1436.     returned string is garbage.
  1437.  
  1438. A:    Make sure that the memory to which the function returns a
  1439.     pointer is correctly allocated.  The returned pointer should be
  1440.     to a statically-allocated buffer, or to a buffer passed in by
  1441.     the caller, but _not_ to a local array.
  1442.  
  1443. 8.5:    You can't use dynamically-allocated memory after you free it,
  1444.     can you?
  1445.  
  1446. A:    No.  Some early man pages for malloc stated that the contents of
  1447.     freed memory was "left undisturbed;" this ill-advised guarantee
  1448.     was never universal and is not required by ANSI.
  1449.  
  1450.     Few programmers would use the contents of freed memory
  1451.     deliberately, but it is easy to do so accidentally.  Consider
  1452.     the following (correct) code for freeing a singly-linked list:
  1453.  
  1454.         struct list *listp, *nextp;
  1455.         for(listp = base; listp != NULL; listp = nextp) {
  1456.             nextp = listp->next;
  1457.             free((char *)listp);
  1458.         }
  1459.  
  1460.     and notice what would happen if the more-obvious loop iteration
  1461.     expression listp = listp->next were used, without the temporary
  1462.     nextp pointer.
  1463.  
  1464.     References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10
  1465.     p. 95.
  1466.  
  1467. 8.6:    How does free() know how many bytes to free?
  1468.  
  1469. A:    The malloc/free package remembers the size of each block it
  1470.     allocates and returns, so it is not necessary to remind it of
  1471.     the size when freeing.
  1472.  
  1473. 8.7:    So can I query the malloc package to find out how big an
  1474.     allocated block is?
  1475.  
  1476. A:    Not portably.
  1477.  
  1478. 8.8:    Is it legal to pass a null pointer as the first argument to
  1479.     realloc()?  Why would you want to?
  1480.  
  1481. A:    ANSI C sanctions this usage (and the related realloc(..., 0),
  1482.     which frees), but several earlier implementations do not support
  1483.     it, so it is not widely portable.  Passing an initially-null
  1484.     pointer to realloc can make it easier to write a self-starting
  1485.     incremental allocation algorithm.
  1486.  
  1487.     References: ANSI Sec. 4.10.3.4 .
  1488.  
  1489. 8.9:    What is the difference between calloc and malloc?  Is it safe to
  1490.     use calloc's zero-fill guarantee for pointer and floating-point
  1491.     values?  Does free work on memory allocated with calloc, or do
  1492.     you need a cfree?
  1493.  
  1494. A:    calloc(m, n) is essentially equivalent to
  1495.  
  1496.         p = malloc(m * n);
  1497.         memset(p, 0, m * n);
  1498.  
  1499.     The zero fill is all-bits-zero, and does not therefore guarantee
  1500.     useful zero values for pointers (see section 1 of this list) or
  1501.     floating-point values.  free can (and should) be used to free
  1502.     the memory allocated by calloc.
  1503.  
  1504.     References: ANSI Secs. 4.10.3 to 4.10.3.2 .
  1505.  
  1506. 8.10:    What is alloca and why is its use discouraged?
  1507.  
  1508. A:    alloca allocates memory which is automatically freed when the
  1509.     function which called alloca returns.  That is, memory allocated
  1510.     with alloca is local to a particular function's "stack frame" or
  1511.     context.
  1512.  
  1513.     alloca cannot be written portably, and is difficult to implement
  1514.     on machines without a stack.  Its use is problematical (and the
  1515.     obvious implementation on a stack-based machine fails) when its
  1516.     return value is passed directly to another function, as in
  1517.     fgets(alloca(100), 100, stdin).
  1518.  
  1519.     For these reasons, alloca cannot be used in programs which must
  1520.     be widely portable, no matter how useful it might be.
  1521.  
  1522.  
  1523. Section 9. Structures
  1524.  
  1525. 9.1:    I heard that structures could be assigned to variables and
  1526.     passed to and from functions, but K&R I says not.
  1527.  
  1528. A:    What K&R I said was that the restrictions on struct operations
  1529.     would be lifted in a forthcoming version of the compiler, and in
  1530.     fact struct assignment and passing were fully functional in
  1531.     Ritchie's compiler even as K&R I was being published.  Although
  1532.     a few early C compilers lacked struct assignment, all modern
  1533.     compilers support it, and it is part of the ANSI C standard, so
  1534.     there should be no reluctance to use it.
  1535.  
  1536.     References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S
  1537.     Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 .
  1538.  
  1539. 9.2:    How does struct passing and returning work?
  1540.  
  1541. A:    When structures are passed as arguments to functions, the entire
  1542.     struct is typically pushed on the stack, using as many words as
  1543.     are required.  (Programmers often choose to use pointers to
  1544.     structures instead, precisely to avoid this overhead.)
  1545.  
  1546.     Structures are often returned from functions in a location
  1547.     pointed to by an extra, compiler-supplied "hidden" argument to
  1548.     the function.  Some older compilers used a special, static
  1549.     location for structure returns, although this made struct-valued
  1550.     functions nonreentrant, which ANSI C disallows.
  1551.  
  1552.     Reference: ANSI Sec. 2.2.3 p. 13.
  1553.  
  1554. 9.3:    The following program works correctly, but it dumps core after
  1555.     it finishes.  Why?
  1556.  
  1557.         struct list
  1558.             {
  1559.             char *item;
  1560.             struct list *next;
  1561.             }
  1562.  
  1563.         /* Here is the main program. */
  1564.  
  1565.         main(argc, argv)
  1566.         ...
  1567.  
  1568. A:    A missing semicolon causes the compiler to believe that main
  1569.     returns a structure.  (The connection is hard to see because of
  1570.     the intervening comment.)  Since struct-valued functions are
  1571.     usually implemented by adding a hidden return pointer, the
  1572.     generated code for main() tries to accept three arguments,
  1573.     although only two are passed (in this case, by the C start-up
  1574.     code).  See also question 16.15.
  1575.  
  1576.     Reference: CT&P Sec. 2.3 pp. 21-2.
  1577.  
  1578. 9.4:    Why can't you compare structs?
  1579.  
  1580. A:    There is no reasonable way for a compiler to implement struct
  1581.     comparison which is consistent with C's low-level flavor.  A
  1582.     byte-by-byte comparison could be invalidated by random bits
  1583.     present in unused "holes" in the structure (such padding is used
  1584.     to keep the alignment of later fields correct).  A field-by-
  1585.     field comparison would require unacceptable amounts of
  1586.     repetitive, in-line code for large structures.
  1587.  
  1588.     If you want to compare two structures, you must write your own
  1589.     function to do so.  C++ would let you arrange for the ==
  1590.     operator to map to your function.
  1591.  
  1592.     References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI
  1593.     Rationale Sec. 3.3.9 p. 47.
  1594.  
  1595. 9.5:    I came across some code that declared a structure like this:
  1596.  
  1597.         struct name
  1598.             {
  1599.             int namelen;
  1600.             char name[1];
  1601.             };
  1602.  
  1603.     and then did some tricky allocation to make the name array act
  1604.     like it had several elements.  Is this legal and/or portable?
  1605.  
  1606. A:    This technique is popular, although Dennis Ritchie has called it
  1607.     "unwarranted chumminess with the compiler."  The ANSI C standard
  1608.     allows it only implicitly.  It seems to be portable to all known
  1609.     implementations.  (Compilers which check array bounds carefully
  1610.     might issue warnings.)
  1611.  
  1612.     References: ANSI Rationale Sec. 3.5.4.2 pp. 54-5.
  1613.  
  1614. 9.6:    How can I determine the byte offset of a field within a
  1615.     structure?
  1616.  
  1617. A:    ANSI C defines the offsetof macro, which should be used if
  1618.     available; see <stddef.h>.  If you don't have it, a suggested
  1619.     implementation is
  1620.  
  1621.         #define offsetof(type, mem) ((size_t) \
  1622.             ((char *)&((type *) 0)->mem - (char *)((type *) 0)))
  1623.  
  1624.     This implementation is not 100% portable; some compilers may
  1625.     legitimately refuse to accept it.
  1626.  
  1627.     See the next question for a usage hint.
  1628.  
  1629.     References: ANSI Sec. 4.1.5 , Rationale Sec. 3.5.4.2 p. 55.
  1630.  
  1631. 9.7:    How can I access structure fields by name at run time?
  1632.  
  1633. A:    Build a table of names and offsets, using the offsetof() macro.
  1634.     The offset of field b in struct a is
  1635.  
  1636.         offsetb = offsetof(struct a, b)
  1637.  
  1638.     If structp is a pointer to an instance of this structure, and b
  1639.     is an int field with offset as computed above, b's value can be
  1640.     set indirectly with
  1641.  
  1642.         *(int *)((char *)structp + offsetb) = value;
  1643.  
  1644.  
  1645. Section 10. Declarations
  1646.  
  1647. 10.1:    How do you decide which integer type to use?
  1648.  
  1649. A:    If you might need large values (above 32767 or below -32767),
  1650.     use long.  Otherwise, if space is very important (there are
  1651.     large arrays or many structures), use short.  Otherwise, use
  1652.     int.  If well-defined overflow characteristics are important
  1653.     and/or negative values are not, use the corresponding unsigned
  1654.     types.  (But beware mixtures of signed and unsigned.)  Similar
  1655.     arguments apply when deciding between float and double.
  1656.  
  1657.     Although char or unsigned char can be used as a "tiny" int type,
  1658.     doing so is often more trouble than it's worth, due to
  1659.     unpredictable sign extension and increased code size.
  1660.  
  1661.     These rules obviously don't apply if the address of a variable
  1662.     is taken and must have a particular type.
  1663.  
  1664. 10.2:    I can't seem to define a linked list successfully.  I tried
  1665.  
  1666.         typedef struct
  1667.             {
  1668.             char *item;
  1669.             NODEPTR next;
  1670.             } *NODEPTR;
  1671.  
  1672.     but the compiler gave me error messages.  Can't a struct in C
  1673.     contain a pointer to itself?
  1674.  
  1675. A:    Structs in C can certainly contain pointers to themselves; the
  1676.     discussion and example in section 6.5 of K&R make this clear.
  1677.     The problem with this example is that the NODEPTR typedef is not
  1678.     complete at the point where the "next" field is declared.  To
  1679.     fix it, first give the structure a tag ("struct node").  Then,
  1680.     declare the "next" field as "struct node *next;", and/or move
  1681.     the typedef declaration wholly before or wholly after the struct
  1682.     declaration.  One fixed version would be
  1683.  
  1684.         struct node
  1685.             {
  1686.             char *item;
  1687.             struct node *next;
  1688.             };
  1689.  
  1690.         typedef struct node *NODEPTR;
  1691.  
  1692.     , and there are at least three other equivalently correct ways
  1693.     of arranging it.
  1694.  
  1695.     A similar problem, with a similar solution, can arise when
  1696.     attempting to declare a pair of typedef'ed mutually recursive
  1697.     structures.
  1698.  
  1699.     References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S
  1700.     Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 .
  1701.  
  1702. 10.3:    How do I declare an array of pointers to functions returning
  1703.     pointers to functions returning pointers to characters?
  1704.  
  1705. A:    This question can be answered in at least three ways (all
  1706.     declare the hypothetical array with 5 elements):
  1707.  
  1708.     1.  char *(*(*a[5])())();
  1709.  
  1710.     2.  Build the declaration up in stages, using typedefs:
  1711.  
  1712.         typedef char *pc;    /* pointer to char */
  1713.         typedef pc fpc();    /* function returning pointer to char */
  1714.         typedef fpc *pfpc;    /* pointer to above */
  1715.         typedef pfpc fpfpc();    /* function returning... */
  1716.         typedef fpfpc *pfpfpc;    /* pointer to... */
  1717.         pfpfpc a[5];        /* array of... */
  1718.  
  1719.     3.  Use the cdecl program, which turns English into C and vice
  1720.         versa:
  1721.  
  1722.         cdecl> declare a as array 5 of pointer to function returning
  1723.              pointer to function returning pointer to char
  1724.         char *(*(*a[5])())()
  1725.  
  1726.         cdecl can also explain complicated declarations, help with
  1727.         casts, and indicate which set of parentheses the arguments
  1728.         go in (for complicated function definitions, like the
  1729.         above).  Versions of cdecl are in volume 14 of
  1730.         comp.sources.unix (see question 16.6) and K&R II.
  1731.  
  1732.     Any good book on C should explain how to read these complicated
  1733.     C declarations "inside out" to understand them ("declaration
  1734.     mimics use").
  1735.  
  1736.     References: K&R II Sec. 5.12 p. 122; H&S Sec. 5.10.1 p. 116.
  1737.  
  1738. 10.4:    What's the best way to declare and define global variables?
  1739.  
  1740. A:    First, though there can be many _declarations_ (and in many
  1741.     translation units) of a single "global" (strictly speaking,
  1742.     "external") variable (or function), there must be exactly one
  1743.     _definition_.  (The definition is the declaration that actually
  1744.     allocates space, and provides an initialization value, if any.)
  1745.     It is best to place the definition in some central (to the
  1746.     program, or to the module) .c file, with an external declaration
  1747.     in a header (".h") file, which is #included wherever the
  1748.     declaration is needed.  The .c file containing the definition
  1749.     should also #include the header file containing the external
  1750.     declaration, so that the compiler can check that the
  1751.     declarations match.
  1752.  
  1753.     This rule promotes a high degree of portability, and is
  1754.     consistent with the requirements of the ANSI C Standard.  Note
  1755.     that Unix compilers and linkers typically use a "common model"
  1756.     which allows multiple (uninitialized) definitions.  A few very
  1757.     odd systems may require an explicit initializer to distinguish a
  1758.     definition from an external declaration.
  1759.  
  1760.     It is possible to use preprocessor tricks to arrange that the
  1761.     declaration need only be typed once, in the header file, and
  1762.     "turned into" a definition, during exactly one #inclusion, via a
  1763.     special #define.
  1764.  
  1765.     References: K&R I Sec. 4.5 pp. 76-7; K&R II Sec. 4.4 pp. 80-1;
  1766.     ANSI Sec. 3.1.2.2 (esp. Rationale), Secs. 3.7, 3.7.2,
  1767.     Sec. F.5.11 .
  1768.  
  1769. 10.5:    I finally figured out the syntax for declaring pointers to
  1770.     functions, but now how do I initialize one?
  1771.  
  1772. A:    Use something like
  1773.  
  1774.         extern int func();
  1775.         int (*fp)() = func;
  1776.  
  1777.     When the name of a function appears in an expression but is not
  1778.     being called (i.e. is not followed by a "("), it "decays" into a
  1779.     pointer (i.e. it has its address implicitly taken), much as an
  1780.     array name does.
  1781.  
  1782.     An explicit extern declaration for the function is normally
  1783.     needed, since implicit external function declaration does not
  1784.     happen in this case (again, because the function name is not
  1785.     followed by a "(").
  1786.  
  1787. 10.6:    I've seen different methods used for calling through pointers to
  1788.     functions.  What's the story?
  1789.  
  1790. A:    Originally, a pointer to a function had to be "turned into" a
  1791.     "real" function, with the * operator (and an extra pair of
  1792.     parentheses, to keep the precedence straight), before calling:
  1793.  
  1794.         int r, f(), (*fp)() = f;
  1795.         r = (*fp)();
  1796.  
  1797.     It can also be argued that functions are always called through
  1798.     pointers, but that "real" functions decay implicitly into
  1799.     pointers (in expressions, as they do in initializations) and so
  1800.     cause no trouble.  This reasoning, made widespread through pcc
  1801.     and adopted in the ANSI standard, means that
  1802.  
  1803.         r = fp();
  1804.  
  1805.     is legal and works correctly, whether fp is a function or a
  1806.     pointer to one.  (The usage has always been unambiguous; there
  1807.     is nothing you ever could have done with a function pointer
  1808.     followed by an argument list except call through it.)  An
  1809.     explicit * is harmless, and still allowed (and recommended, if
  1810.     portability to older compilers is important).
  1811.  
  1812.     References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41.
  1813.  
  1814.  
  1815. Section 11. Boolean Expressions and Variables
  1816.  
  1817. 11.1:    What is the right type to use for boolean values in C?  Why
  1818.     isn't it a standard type?  Should #defines or enums be used for
  1819.     the true and false values?
  1820.  
  1821. A:    C does not provide a standard boolean type, because picking one
  1822.     involves a space/time tradeoff which is best decided by the
  1823.     programmer.  (Using an int for a boolean may be faster, while
  1824.     using char may save data space.)
  1825.  
  1826.     The choice between #defines and enums is arbitrary and not
  1827.     terribly interesting.  Use any of
  1828.  
  1829.         #define TRUE  1            #define YES 1
  1830.         #define FALSE 0            #define NO  0
  1831.  
  1832.         enum bool {false, true};    enum bool {no, yes};
  1833.  
  1834.     or use raw 1 and 0, as long as you are consistent within one
  1835.     program or project.  (An enum may be preferable if your debugger
  1836.     expands enum values when examining variables.)
  1837.  
  1838.     Some people prefer variants like
  1839.  
  1840.         #define TRUE (1==1)
  1841.         #define FALSE (!TRUE)
  1842.  
  1843.     or define "helper" macros such as
  1844.  
  1845.         #define Istrue(e) ((e) != 0)
  1846.  
  1847.     These don't buy anything (see below).
  1848.  
  1849. 11.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  1850.     is considered "true" in C?  What if a built-in boolean or
  1851.     relational operator "returns" something other than 1?
  1852.  
  1853. A:    It is true (sic) that any nonzero value is considered true in C,
  1854.     but this applies only "on input", i.e. where a boolean value is
  1855.     expected.  When a boolean value is generated by a built-in
  1856.     operator, it is guaranteed to be 1 or 0.  Therefore, the test
  1857.  
  1858.         if((a == b) == TRUE)
  1859.  
  1860.     will work as expected (as long as TRUE is 1), but it is
  1861.     obviously silly.  In general, explicit tests against TRUE and
  1862.     FALSE are undesirable, because some library functions (notably
  1863.     isupper, isalpha, etc.) return, on success, a nonzero value
  1864.     which is _not_ necessarily 1.  (Besides, if you believe that
  1865.     "if((a == b) == TRUE)" is an improvement over "if(a == b)", why
  1866.     stop there?  Why not use "if(((a == b) == TRUE) == TRUE)"?)  A
  1867.     good rule of thumb is to use TRUE and FALSE (or the like) only
  1868.     for assignment to a Boolean variable, or as the return value
  1869.     from a Boolean function, never in a comparison.
  1870.  
  1871.     The preprocessor macros TRUE and FALSE (and, of course, NULL)
  1872.     are used for code readability, not because the underlying values
  1873.     might ever change.  (See also question 1.7.)
  1874.  
  1875.     References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42,
  1876.     Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8,
  1877.     3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5; Achilles and the
  1878.     Tortoise.
  1879.  
  1880. 11.3:    What is the difference between an enum and a series of
  1881.     preprocessor #defines?
  1882.  
  1883. A:    At the present time, there is little difference.  Although many
  1884.     people might have wished otherwise, the ANSI standard says that
  1885.     enumerations may be freely intermixed with integral types,
  1886.     without errors.  (If such intermixing were disallowed without
  1887.     explicit casts, judicious use of enums could catch certain
  1888.     programming errors.)
  1889.  
  1890.     The primary advantages of enums are that the numeric values are
  1891.     automatically assigned, and that a debugger may be able to
  1892.     display the symbolic values when enum variables are examined.
  1893.     (A compiler may also generate nonfatal warnings when enums and
  1894.     ints are indiscriminately mixed, since doing so can still be
  1895.     considered bad style even though it is not strictly illegal).  A
  1896.     disadvantage is that the programmer has little control over the
  1897.     size (or over those nonfatal warnings).
  1898.  
  1899.     References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S
  1900.     Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 .
  1901.  
  1902.  
  1903. Section 12. System Dependencies
  1904.  
  1905. 12.1:    How can I read a single character from the keyboard without
  1906.     waiting for a newline?
  1907.  
  1908. A:    Contrary to popular belief and many people's wishes, this is not
  1909.     a C-related question.  (Nor are closely-related questions
  1910.     concerning the echo of keyboard input.)  The delivery of
  1911.     characters from a "keyboard" to a C program is a function of the
  1912.     operating system in use, and cannot be standardized by the C
  1913.     language.  Some versions of curses have a cbreak() function
  1914.     which does what you want.  Under UNIX, use ioctl to play with
  1915.     the terminal driver modes (CBREAK or RAW under "classic"
  1916.     versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or
  1917.     Posix systems).  Under MS-DOS, use getch().  Under VMS, try the
  1918.     Screen Management (SMG$) routines.  Under other operating
  1919.     systems, you're on your own.  Beware that some operating systems
  1920.     make this sort of thing impossible, because character collection
  1921.     into input lines is done by peripheral processors not under
  1922.     direct control of the CPU running your program.
  1923.  
  1924.     Operating system specific questions are not appropriate for
  1925.     comp.lang.c .  Many common questions are answered in
  1926.     frequently-asked questions postings in such groups as
  1927.     comp.unix.questions and comp.os.msdos.programmer .  Note that
  1928.     the answers are often not unique even across different variants
  1929.     of a system; bear in mind when answering system-specific
  1930.     questions that the answer that applies to your system may not
  1931.     apply to everyone else's.
  1932.  
  1933.     References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1.
  1934.  
  1935. 12.2:    How can I find out if there are characters available for reading
  1936.     (and if so, how many)?  Alternatively, how can I do a read that
  1937.     will not block if there are no characters available?
  1938.  
  1939. A:    These, too, are entirely operating-system-specific.  Some
  1940.     versions of curses have a nodelay() function.  Depending on your
  1941.     system, you may also be able to use "nonblocking I/O", or a
  1942.     system call named "select", or the FIONREAD ioctl, or kbhit(),
  1943.     or rdchk(), or the O_NDELAY option to open() or fcntl().
  1944.  
  1945. 12.3:    How do I read the mouse?
  1946.  
  1947. A:    Consult your system documentation, or ask on an appropriate
  1948.     system-specific newsgroup (but check its FAQ list first).  Mouse
  1949.     handling is completely different under the X window system than
  1950.     it is under MS-DOS than it is on the Macintosh.
  1951.  
  1952. 12.4:    How can my program discover the complete pathname to the
  1953.     executable file from which it was invoked?
  1954.  
  1955. A:    argv[0] may contain all or part of the pathname, or it may
  1956.     contain nothing.  You may be able to duplicate the command
  1957.     language interpreter's search path logic to locate the
  1958.     executable if the name in argv[0] is present but incomplete.
  1959.     However, there is no guaranteed or portable solution.
  1960.  
  1961. 12.5:    How can a process change an environment variable in its caller?
  1962.  
  1963. A:    In general, it cannot.  Different operating systems implement
  1964.     name/value functionality similar to the Unix environment in
  1965.     different ways.  Whether the "environment" can be usefully
  1966.     altered by a running program, and if so, how, is system-
  1967.     dependent.
  1968.  
  1969.     Under Unix, a process can modify its own environment (some
  1970.     systems provide setenv() and/or putenv() functions to do this),
  1971.     and the modified environment is usually passed on to any child
  1972.     processes, but it is _not_ propagated back to the parent
  1973.     process.
  1974.  
  1975. 12.6:    How can I find out the size of a file, prior to reading it in?
  1976.  
  1977. A:    If the "size of a file" is the number of characters you'll be
  1978.     able to read from it in C, it is in general impossible to
  1979.     determine this number in advance.  Under Unix, the stat()
  1980.     function will give you an exact answer, and several other
  1981.     systems supply a Unix-like stat() which will give an approximate
  1982.     answer.  You can fseek to the end and then use ftell, but this
  1983.     usage is nonportable (it gives you an accurate answer only under
  1984.     Unix, and a guaranteed, but potentially approximate answer only
  1985.     for ANSI C "binary" files).
  1986.  
  1987. 12.7:    How can a file be shortened in-place without completely clearing
  1988.     or rewriting it?
  1989.  
  1990. A:    BSD systems provide ftruncate(), several others supply chsize(),
  1991.     and a few may provide a (possibly undocumented) fcntl option
  1992.     F_FREESP, but there is no truly portable solution.
  1993.  
  1994. 12.8:    How can I implement a delay, or time a user's response, with
  1995.     sub-second resolution?
  1996.  
  1997. A:    Unfortunately, there is no portable way.  V7 Unix, and derived
  1998.     systems, provided a fairly useful ftime() routine with
  1999.     resolution up to a millisecond, but it has disappeared from
  2000.     System V and Posix.
  2001.  
  2002.  
  2003. Section 13. Stdio
  2004.  
  2005. 13.1:    Why does errno contain ENOTTY after a call to printf?
  2006.  
  2007. A:    Many implementations of the stdio package adjust their behavior
  2008.     slightly if stdout is a terminal.  To make the determination,
  2009.     these implementations perform an operation which fails (with
  2010.     ENOTTY) if stdout is not a terminal.  Although the output
  2011.     operation goes on to complete successfully, errno still contains
  2012.     ENOTTY.
  2013.  
  2014.     Reference: CT&P Sec. 5.4 p. 73.
  2015.  
  2016. 13.2:    My program's prompts and intermediate output don't always show
  2017.     up on the screen, especially when I pipe the output through
  2018.     another program.
  2019.  
  2020. A:    It is best to use an explicit fflush(stdout) whenever output
  2021.     should definitely be visible.  Several mechanisms attempt to
  2022.     perform the fflush for you, at the "right time," but they tend
  2023.     to apply only when stdout is a terminal.  (See question 13.1.)
  2024.  
  2025. 13.3:    When I read from the keyboard with scanf(), it seems to hang
  2026.     until I type one extra line of input.
  2027.  
  2028. A:    scanf() was designed for free-format input, which is seldom what
  2029.     you want when reading from the keyboard.  In particular, "\n" in
  2030.     a format string means, not to expect a newline, but to read and
  2031.     discard characters as long as each is a whitespace character.
  2032.  
  2033.     It is usually better to use fgets() to read a whole line, and
  2034.     then use sscanf() or other string functions to parse the line
  2035.     buffer.
  2036.  
  2037. 13.4:    How can I flush pending input so that a user's typeahead isn't
  2038.     read at the next prompt?  Will fflush(stdin) work?
  2039.  
  2040. A:    fflush is defined only for output streams.  Since its definition
  2041.     of "flush" is to complete the writing of buffered characters
  2042.     (not to discard them), discarding unread input would not be an
  2043.     analogous meaning for fflush on input streams.  There is no
  2044.     standard way to discard unread characters from a stdio input
  2045.     buffer, nor would such a way be sufficient; unread characters
  2046.     can also accumulate in other, OS-level input buffers.
  2047.  
  2048. 13.5:    How can I recover the file name given an open file descriptor?
  2049.  
  2050. A:    This problem is, in general, insoluble.  Under Unix, for
  2051.     instance, a scan of the entire disk, (perhaps requiring special
  2052.     permissions) would theoretically be required, and would fail if
  2053.     the file descriptor was a pipe or referred to a deleted file
  2054.     (and could give a misleading answer for a file with multiple
  2055.     links).  It is best to remember the names of open files yourself
  2056.     (perhaps with a wrapper function around fopen).
  2057.  
  2058.  
  2059. Section 14. Library Subroutines
  2060.  
  2061. 14.1:    I'm trying to sort an array of strings with qsort, using strcmp
  2062.     as the comparison function, but it's not working.
  2063.  
  2064. A:    By "array of strings" you probably mean "array of pointers to
  2065.     char."  The arguments to qsort's comparison function are
  2066.     pointers to the objects being sorted, in this case, pointers to
  2067.     pointers to char.  (strcmp, of course, accepts simple pointers
  2068.     to char.)
  2069.  
  2070.     The comparison routine's arguments are expressed as "generic
  2071.     pointers," void * or char *.  They must be converted back to
  2072.     what they "really are" (char **) and dereferenced, yielding
  2073.     char *'s which can be usefully compared.  Write a comparison
  2074.     function like this:
  2075.  
  2076.         int pstrcmp(p1, p2)    /* compare strings through pointers */
  2077.         char *p1, *p2;        /* void * for ANSI C */
  2078.         {
  2079.             return strcmp(*(char **)p1, *(char **)p2);
  2080.         }
  2081.  
  2082. 14.2:    Now I'm trying to sort an array of structures with qsort.  My
  2083.     comparison routine takes pointers to structures, but the
  2084.     compiler complains that the function is of the wrong type for
  2085.     qsort.  How can I cast the function pointer to shut off the
  2086.     warning?
  2087.  
  2088. A:    The conversions must be in the comparison function, which must
  2089.     be declared as accepting "generic pointers" (void * or char *)
  2090.     as discussed above.
  2091.  
  2092. 14.3:    How can I convert numbers to strings (the opposite of atoi)?
  2093.     Is there an itoa function?
  2094.  
  2095. A:    Just use sprintf.  (You'll have to allocate space for the result
  2096.     somewhere anyway; see questions 8.1 and 8.2.  Don't worry that
  2097.     sprintf may be overkill, potentially wasting run time or code
  2098.     space; it works well in practice.)
  2099.  
  2100.     References: K&R I Sec. 3.6 p. 60; K&R II Sec. 3.6 p. 64.
  2101.  
  2102. 14.4:    How can I get the time of day in a C program?
  2103.  
  2104. A:    Just use the time, ctime, and/or localtime functions.  (These
  2105.     routines have been around for years, and are in the ANSI
  2106.     standard.)  Here is a simple example:
  2107.  
  2108.         #include <stdio.h>
  2109.         #include <time.h>
  2110.  
  2111.         main()
  2112.         {
  2113.             time_t now;
  2114.             time(&now);
  2115.             printf("It's %.24s.\n", ctime(&now));
  2116.             exit(0);
  2117.         }
  2118.  
  2119.     References: ANSI Sec. 4.12 .
  2120.  
  2121. 14.5:    I know that the library routine localtime will convert a time_t
  2122.     into a broken-down struct tm, and that ctime will convert a
  2123.     time_t to a printable string.  How can I perform the inverse
  2124.     operations of converting a struct tm or a string into a time_t?
  2125.  
  2126. A:    ANSI C specifies a library routine, mktime, which converts a
  2127.     struct tm to a time_t.  Several public-domain versions of this
  2128.     routine are available in case your compiler does not support it
  2129.     yet.
  2130.  
  2131.     Converting a string to a time_t is harder, because of the wide
  2132.     variety of date and time formats which should be parsed.
  2133.     Public-domain routines have been written for performing this
  2134.     function (see, for example, the file partime.c, widely
  2135.     distributed with the RCS package), but they are less likely to
  2136.     become standardized.
  2137.  
  2138.     References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI
  2139.     Sec. 4.12.2.3 .
  2140.  
  2141. 14.6:    I need a random number generator.
  2142.  
  2143. A:    The standard C library has one: rand().  The implementation on
  2144.     your system may not be perfect, but writing a better one isn't
  2145.     necessarily easy, either.
  2146.  
  2147.     References: ANSI Sec. 4.10.2.1 p. 154.
  2148.  
  2149. 14.7:    Each time I run my program, I get the same sequence of random
  2150.     numbers.
  2151.  
  2152. A:    You can call srand() to seed the pseudo-random number generator
  2153.     with a more random value.  Popular random initial seeds are the
  2154.     time of day, or the elapsed time before the user presses a key.
  2155.  
  2156.     References: ANSI Sec. 4.10.2.2 p. 154.
  2157.  
  2158. 14.8:    I need a random true/false value, so I'm taking rand() % 2, but
  2159.     it's just alternating 0, 1, 0, 1, 0...
  2160.  
  2161. A:    Poor pseudorandom number generators (such as the ones
  2162.     unfortunately supplied with some systems) are not very random in
  2163.     the low-order bits.  Try using the higher-order bits.
  2164.  
  2165. 14.9-13: I'm trying to port this old    A:  These routines are variously
  2166.     program.  Why do I get            obsolete; you should
  2167.     "undefined external" errors        instead:
  2168.     for:
  2169.  
  2170. 14.9:    index?                A:  use strchr.
  2171. 14.10:    rindex?                A:  use strrchr.
  2172. 14.11:    bcopy?                A:  use memmove, after
  2173.                         interchanging the first and
  2174.                         second arguments (see also
  2175.                         question 4.10).
  2176. 14.12:    bcmp?                A:  use memcmp.
  2177. 14.13:    bzero?                A:  use memset, with a second
  2178.                         argument of 0.
  2179.  
  2180. 14.14:    How can I execute a command with system() and read its output
  2181.     into a program?
  2182.  
  2183. A:    Unix and some other systems provide a popen() routine, which
  2184.     sets up a stdio stream on a pipe connected to the process
  2185.     running a command, so that the output can be read (or the input
  2186.     supplied).
  2187.  
  2188. 14.15:    How can I read a directory in a C program?
  2189.  
  2190. A:    See if you can use the opendir() and readdir() routines, which
  2191.     are available on most Unix systems.  Implementations also exist
  2192.     for MS-DOS, VMS, and other systems.  (MS-DOS also has FINDFIRST
  2193.     and FINDNEXT routines which do essentially the same thing.)
  2194.  
  2195.  
  2196. Section 15. Style
  2197.  
  2198. 15.1:    Here's a neat trick:
  2199.  
  2200.         if(!strcmp(s1, s2))
  2201.  
  2202.     Is this good style?
  2203.  
  2204. A:    Perhaps; perhaps not.  The test succeeds if the two strings are
  2205.     equal, but its form suggests that it tests for inequality.
  2206.  
  2207.     Another solution is to use a macro:
  2208.  
  2209.         #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
  2210.  
  2211.     Opinions on code style, like those on religion, can be debated
  2212.     endlessly.  Though good style is a worthy goal, and can usually
  2213.     be recognized, it cannot be codified.
  2214.  
  2215. 15.2:    What's the best style for code layout in C?
  2216.  
  2217. A:    K&R, while providing the example most often copied, also supply
  2218.     a good excuse for avoiding it:
  2219.  
  2220.         The position of braces is less important,
  2221.         although people hold passionate beliefs.
  2222.         We have chosen one of several popular styles.
  2223.         Pick a style that suits you, then use it
  2224.         consistently.
  2225.  
  2226.     It is more important that the layout chosen be consistent (with
  2227.     itself, and with nearby or common code) than that it be
  2228.     "perfect."  If your coding environment (i.e. local custom or
  2229.     company policy) does not suggest a style, and you don't feel
  2230.     like inventing your own, just copy K&R.  (The tradeoffs between
  2231.     various indenting and brace placement options can be
  2232.     exhaustively and minutely examined, but don't warrant repetition
  2233.     here.  See also the Indian Hill Style Guide.)
  2234.  
  2235.     The elusive quality of "good style" involves much more than mere
  2236.     code layout details; don't spend time on formatting to the
  2237.     exclusion of more substantive code quality issues.
  2238.  
  2239.     Reference: K&R Sec. 1.2 p. 10.
  2240.  
  2241. 15.3:    Where can I get the "Indian Hill Style Guide" and other coding
  2242.     standards?
  2243.  
  2244. A:    Various documents are available for anonymous ftp from:
  2245.  
  2246.         Site:            File or directory:
  2247.  
  2248.         cs.washington.edu        ~ftp/pub/cstyle.tar.Z
  2249.         (128.95.1.4)        (the updated Indian Hill guide)
  2250.  
  2251.         cs.toronto.edu        doc/programming
  2252.  
  2253.         giza.cis.ohio-state.edu    pub/style-guide
  2254.  
  2255.  
  2256. Section 16. Miscellaneous
  2257.  
  2258. 16.1:    What can I safely assume about the initial values of variables
  2259.     which are not explicitly initialized?  If global variables start
  2260.     out as "zero," is that good enough for null pointers and
  2261.     floating-point zeroes?
  2262.  
  2263. A:    Variables with "static" duration (that is, those declared
  2264.     outside of functions, and those declared with the storage class
  2265.     static), are guaranteed initialized to zero, as if the
  2266.     programmer had typed "= 0".  Therefore, such variables are
  2267.     initialized to the null pointer (of the correct type) if they
  2268.     are pointers, and to 0.0 if they are floating-point.
  2269.  
  2270.     Variables with "automatic" duration (i.e. local variables
  2271.     without the static storage class) start out containing garbage,
  2272.     unless they are explicitly initialized.  Nothing useful can be
  2273.     predicted about the garbage.
  2274.  
  2275.     Dynamically-allocated memory obtained with malloc and realloc is
  2276.     also likely to contain garbage, and must be initialized by the
  2277.     calling program, as appropriate.  Memory obtained with calloc
  2278.     contains all-bits-0, but this is not necessarily useful for
  2279.     pointer or floating-point values (see section 1 and question
  2280.     8.9).
  2281.  
  2282. 16.2:    How can I write data files which can be read on other machines
  2283.     with different word size, byte order, or floating point formats?
  2284.  
  2285. A:    The best solution is to use text files (usually ASCII), written
  2286.     with fprintf and read with fscanf or the like.  (Similar advice
  2287.     also applies to network protocols.)  Be skeptical of arguments
  2288.     which imply that text files are too big, or that reading and
  2289.     writing them is too slow.  Not only is their efficiency
  2290.     frequently acceptable in practice, but the advantages of being
  2291.     able to manipulate them with standard tools can be overwhelming.
  2292.  
  2293.     If you must use a binary format, you can improve portability,
  2294.     and perhaps take advantage of prewritten I/O libraries, by
  2295.     making use of standardized formats such as Sun's XDR (RFC 1014),
  2296.     OSI's ASN.1, CCITT's X.409, or ISO 8825 "Basic Encoding Rules."
  2297.  
  2298. 16.3:    I seem to be missing the system header file <sgtty.h>.  Can
  2299.     someone send me a copy?
  2300.  
  2301. A:    Standard headers exist in part so that definitions appropriate
  2302.     to your compiler, operating system, and processor can be
  2303.     supplied.  You cannot just pick up a copy of someone else's
  2304.     header file and expect it to work, unless that person is using
  2305.     exactly the same environment.  Ask your compiler vendor why the
  2306.     file was not provided (or to send a replacement copy).
  2307.  
  2308. 16.4:    How can I call Fortran (BASIC, Pascal, ADA, lisp) functions from
  2309.     C?  (And vice versa?)
  2310.  
  2311. A:    The answer is entirely dependent on the machine and the specific
  2312.     calling sequences of the various compilers in use, and may not
  2313.     be possible at all.  Read your compiler documentation very
  2314.     carefully; sometimes there is a "mixed-language programming
  2315.     guide," although the techniques for passing arguments and
  2316.     ensuring correct run-time startup are often arcane.
  2317.  
  2318.     cfortran.h, a C header file, simplifies C/Fortran interfacing on
  2319.     many popular machines.  It is available via anonymous ftp from
  2320.     zebra.desy.de (131.169.2.244).
  2321.  
  2322. 16.5:    Does anyone know of a program for converting Pascal (Fortran,
  2323.     lisp, "Old" C, ...) to C?
  2324.  
  2325. A:    Several public-domain programs are available:
  2326.  
  2327.     p2c    written by Dave Gillespie, and posted to
  2328.         comp.sources.unix in March, 1990 (Volume 21); also
  2329.         available by anonymous ftp from csvax.cs.caltech.edu,
  2330.         file pub/p2c-1.20.tar.Z .
  2331.  
  2332.     ptoc    another comp.sources.unix contribution, this one written
  2333.         in Pascal (comp.sources.unix, Volume 10, also patches in
  2334.         Volume 13?).
  2335.  
  2336.     f2c    jointly developed by people from Bell Labs, Bellcore,
  2337.         and Carnegie Mellon.  To find about f2c, send the mail
  2338.         message "send index from f2c" to netlib@research.att.com
  2339.         or research!netlib.  (It is also available via anonymous
  2340.         ftp on research.att.com, in directory dist/f2c.)
  2341.  
  2342.     A PL/M to C converter was posted to alt.sources in April, 1991.
  2343.  
  2344.     The following companies sell various translation tools and
  2345.     services:
  2346.  
  2347.         Cobalt Blue
  2348.         2940 Union Ave., Suite C
  2349.         San Jose, CA  95124  USA
  2350.         (+1) 408 723 0474
  2351.  
  2352.         Promula Development Corp.
  2353.         3620 N. High St., Suite 301
  2354.         Columbus, OH  43214  USA
  2355.         (+1) 614 263 5454
  2356.  
  2357.         Micro-Processor Services Inc.
  2358.         92 Stone Hurst Lane
  2359.         Dix Hills, NY  11746  USA
  2360.         (+1) 519 499 4461
  2361.  
  2362.     See also question 4.3.
  2363.  
  2364. 16.6:    Where can I get copies of all these public-domain programs?
  2365.  
  2366. A:    If you have access to Usenet, see the regular postings in the
  2367.     comp.sources.unix and comp.sources.misc newsgroups, which
  2368.     describe, in some detail, the archiving policies and how to
  2369.     retrieve copies.  The usual approach is to use anonymous ftp
  2370.     and/or uucp from a central, public-spirited site, such as uunet
  2371.     (ftp.uu.net, 192.48.96.9).  However, this article cannot track
  2372.     or list all of the available archive sites and how to access
  2373.     them.  The comp.archives newsgroup contains numerous
  2374.     announcements of anonymous ftp availability of various items.
  2375.     The "archie" mailserver can tell you which anonymous ftp sites
  2376.     have which packages; send the mail message "help" to
  2377.     archie@quiche.cs.mcgill.ca for information.  Finally, the
  2378.     newsgroup comp.sources.wanted is generally a more appropriate
  2379.     place to post queries for source availability, but check _its_
  2380.     FAQ list, "How to find sources," before posting there.
  2381.  
  2382. 16.7:    When will the next International Obfuscated C Code Contest
  2383.     (IOCCC) be held?  How can I get a copy of the current and
  2384.     previous winning entries?
  2385.  
  2386. A:    The contest typically runs from early March through mid-May.  To
  2387.     obtain a current copy of the rules and other information, send
  2388.     e-mail with the Subject: line "send rules" to:
  2389.  
  2390.         {apple,pyramid,sun,uunet}!hoptoad!judges  or  judges@toad.com
  2391.  
  2392.     Contest winners are first announced at the Summer Usenix
  2393.     Conference in mid-June, and posted to the net in July.  Previous
  2394.     winners are available on uunet (see question 16.6) under the
  2395.     directory ~/pub/ioccc.
  2396.  
  2397. 16.8:    Why don't C comments nest?  Are they legal inside quoted
  2398.     strings?
  2399.  
  2400. A:    Nested comments would cause more harm than good, mostly because
  2401.     of the possibility of accidentally leaving comments unclosed by
  2402.     including the characters "/*" within them.  For this reason, it
  2403.     is usually better to "comment out" large sections of code, which
  2404.     might contain comments, with #ifdef or #if 0 (but see question
  2405.     4.7).
  2406.  
  2407.     The character sequences /* and */ are not special within
  2408.     double-quoted strings, and do not therefore introduce comments,
  2409.     because a program (particularly one which is generating C code
  2410.     as output) might want to print them.
  2411.  
  2412.     Reference: ANSI Rationale Sec. 3.1.9 p. 33.
  2413.  
  2414. 16.9:    What is the most efficient way to count the number of bits which
  2415.     are set in a value?
  2416.  
  2417. A:    This and many other similar bit-twiddling problems can often be
  2418.     sped up and streamlined using lookup tables (but see the next
  2419.     question).
  2420.  
  2421. 16.10:    How can I make this code more efficient?
  2422.  
  2423. A:    Efficiency, though a favorite comp.lang.c topic, is not
  2424.     important nearly as often as people tend to think it is.  Most
  2425.     of the code in most programs is not time-critical.  When code is
  2426.     not time-critical, it is far more important that it be written
  2427.     clearly and portably than that it be written maximally
  2428.     efficiently.  (Remember that computers are very, very fast, and
  2429.     that even "inefficient" code can run without apparent delay.)
  2430.  
  2431.     It is notoriously difficult to predict what the "hot spots" in a
  2432.     program will be.  When efficiency is a concern, it is important
  2433.     to use profiling software to determine which parts of the
  2434.     program deserve attention.  Often, actual computation time is
  2435.     swamped by peripheral tasks such as I/O and memory allocation,
  2436.     which can be sped up by using buffering and cacheing techniques.
  2437.  
  2438.     For the small fraction of code that is time-critical, it is
  2439.     vital to pick a good algorithm; it is less important to
  2440.     "microoptimize" the coding details.  Many of the "efficient
  2441.     coding tricks" which are frequently suggested (e.g. substituting
  2442.     shift operators for multiplication by powers of two) are
  2443.     performed automatically by even simpleminded compilers.
  2444.     Heavyhanded "optimization" attempts can make code so bulky that
  2445.     performance is degraded.
  2446.  
  2447.     For more discussion of efficiency tradeoffs, as well as good
  2448.     advice on how to increase efficiency when it is important, see
  2449.     chapter 7 of Kernighan and Plauger's The Elements of Programming
  2450.     Style, and Jon Bentley's Writing Efficient Programs.
  2451.  
  2452. 16.11:    Are pointers really faster than arrays?  How much do function
  2453.     calls slow things down?  Is ++i faster than i = i + 1?
  2454.  
  2455. A:    Precise answers to these and many similar questions depend of
  2456.     course on the processor and compiler in use.  If you simply must
  2457.     know, you'll have to time test programs carefully.  (Often the
  2458.     differences are so slight that hundreds of thousands of
  2459.     iterations are required even to see them.  Check the compiler's
  2460.     assembly language output, if available, to see if two purported
  2461.     alternatives aren't compiled identically.)
  2462.  
  2463.     It is "usually" faster to march through large arrays with
  2464.     pointers rather than array subscripts, but for some processors
  2465.     the reverse is true.
  2466.  
  2467.     Function calls, though obviously incrementally slower than in-
  2468.     line code, contribute so much to modularity and code clarity
  2469.     that there is rarely good reason to avoid them.
  2470.  
  2471.     Before rearranging expressions such as i = i + 1, remember that
  2472.     you are dealing with a C compiler, not a keystroke-programmable
  2473.     calculator.  A good compiler will generate identical code for
  2474.     ++i, i += 1, and i = i + 1.  The reasons for using ++i or i += 1
  2475.     over i = i + 1 have to do with style, not efficiency.  (See also
  2476.     question 3.3.)
  2477.  
  2478. 16.12:    My floating-point calculations are acting strangely and giving
  2479.     me different answers on different machines.
  2480.  
  2481. A:    First, make sure that you have #included <math.h>, and correctly
  2482.     declared other functions returning double.
  2483.  
  2484.     If the problem isn't that simple, recall that most digital
  2485.     computers use floating-point formats which provide a close but
  2486.     by no means exact simulation of real number arithmetic.  Among
  2487.     other things, the associative and distributive laws do not hold
  2488.     completely (i.e. order of operation may be important, and
  2489.     repeated addition is not necessarily equivalent to
  2490.     multiplication).  Underflow or cumulative precision loss is
  2491.     often a problem.
  2492.  
  2493.     Don't assume that floating-point results will be exact, and
  2494.     especially don't assume that floating-point values can be
  2495.     compared for equality.  (Don't throw haphazard "fuzz factors"
  2496.     in, either.)
  2497.  
  2498.     These problems are no worse for C than they are for any other
  2499.     computer language.  Floating-point semantics are usually defined
  2500.     as "however the processor does them;" otherwise a compiler for a
  2501.     machine without the "right" model would have to do prohibitively
  2502.     expensive emulations.
  2503.  
  2504.     This article cannot begin to list the pitfalls associated with,
  2505.     and workarounds appropriate for, floating-point work.  A good
  2506.     programming text should cover the basics.
  2507.  
  2508.     References: EoPS Sec. 6 pp. 115-8.
  2509.  
  2510. 16.13:    Why doesn't C have an exponentiation operator?
  2511.  
  2512. A:    You can #include <math.h> and use the pow() function, although
  2513.     explicit multiplication is often better for small integral
  2514.     exponents.
  2515.  
  2516.     References: ANSI Sec. 4.5.5.1 .
  2517.  
  2518. 16.14:    I'm having trouble with a Turbo C program which crashes and says
  2519.     something like "floating point formats not linked."
  2520.  
  2521. A:    Some compilers for small machines, including Turbo C (and
  2522.     Ritchie's original PDP-11 compiler), leave out floating point
  2523.     support if it looks like it will not be needed.  In particular,
  2524.     the non-floating-point versions of printf and scanf save space
  2525.     by not including code to handle %e, %f, and %g.  It happens that
  2526.     Turbo C's heuristics for determining whether the program uses
  2527.     floating point are occasionally insufficient, and the programmer
  2528.     must sometimes insert a dummy explicit floating-point call to
  2529.     force loading of floating-point support.
  2530.  
  2531.     In general, questions about a particular compiler are
  2532.     inappropriate for comp.lang.c .  Problems with PC compilers, for
  2533.     instance, will find a more receptive audience in a PC newsgroup
  2534.     (e.g. comp.os.msdos.programmer).
  2535.  
  2536. 16.15:    This program crashes before it even runs!  (When single-stepping
  2537.     with a debugger, it dies before the first statement in main.)
  2538.  
  2539. A:    You probably have one or more very large (kilobyte or more)
  2540.     local arrays.  Many systems have fixed-size stacks, and those
  2541.     which perform dynamic stack allocation automatically (e.g. Unix)
  2542.     can be confused when the stack tries to grow by a huge chunk all
  2543.     at once.
  2544.  
  2545.     It is often better to declare large arrays with static duration
  2546.     (unless of course you need a fresh set with each recursive
  2547.     call).
  2548.  
  2549.     (See also question 9.3.)
  2550.  
  2551. 16.16:    What does "Segmentation violation" mean?
  2552.  
  2553. A:    It means your program tried to access memory it shouldn't have,
  2554.     invariably as a result of improper pointer use, often involving
  2555.     malloc.
  2556.  
  2557. 16.17:    Does anyone have a C compiler test suite I can use?
  2558.  
  2559. A:    Plum Hall (1 Spruce Ave., Cardiff, NJ 08232, USA), among others,
  2560.     sells one.
  2561.  
  2562. 16.18:    Where can I get a YACC grammar for C?
  2563.  
  2564. A:    The definitive grammar is of course the one in the ANSI
  2565.     standard.  Several copies are floating around; keep your eyes
  2566.     open.  There is one on uunet (see question 16.6) in
  2567.     usenet/net.sources/ansi.c.grammar.Z (including a companion
  2568.     lexer).  The FSF's GNU C compiler contains a grammar, as does
  2569.     the appendix to K&R II.
  2570.  
  2571.     References: ANSI Sec. A.2 .
  2572.  
  2573. 16.19:    How do you pronounce "char"?  What's that funny name for the "#"
  2574.     character?
  2575.  
  2576. A:    You can pronounce the C keyword "char" in at least three ways:
  2577.     like the English words "char," "care," or "car;" the choice is
  2578.     arbitrary.  Bell Labs once proposed the (now obsolete) term
  2579.     "octothorpe" for the "#" character.
  2580.  
  2581.     Trivia questions like these aren't any more pertinent for
  2582.     comp.lang.c than they are for most of the other groups they
  2583.     frequently come up in.  You can find lots of information in the
  2584.     net.announce.newusers frequently-asked questions postings, the
  2585.     "jargon file" (also published as _The [New] Hacker's
  2586.     Dictionary_), and the old Usenet ASCII pronunciation list.
  2587.  
  2588. 16.20:    Where can I get extra copies of this list?  What about back
  2589.     issues?
  2590.  
  2591. A:    For now, just pull it off the net; it is normally posted to
  2592.     comp.lang.c on the first of each month, with an Expiration: line
  2593.     which should keep it around all month.  It can also be found in
  2594.     the newsgroup news.answers .  Several sites archive news.answers
  2595.     postings and other FAQ lists, including this one; the archie
  2596.     server (see question 16.6) should help you find them.  See the
  2597.     meta-FAQ list in news.answers for more information.
  2598.  
  2599.     This list is an evolving document, not just a collection of this
  2600.     month's interesting questions.  Older copies are obsolete and
  2601.     don't contain much, except the occasional typo, that the current
  2602.     list doesn't.
  2603.  
  2604.  
  2605. Bibliography
  2606.  
  2607. ANSI    American National Standard for Information Systems --
  2608.     Programming Language -- C, ANSI X3.159-1989 (see question 4.2).
  2609.  
  2610. JLB    Jon Louis Bentley, Writing Efficient Programs, Prentice-Hall,
  2611.     1982, ISBN 0-13-970244-X.
  2612.  
  2613. H&S    Samuel P. Harbison and Guy L. Steele, C: A Reference Manual,
  2614.     Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0.
  2615.     (A third edition has recently been released.)
  2616.  
  2617. PCS    Mark R. Horton, Portable C Software, Prentice Hall, 1990,
  2618.     ISBN 0-13-868050-7.
  2619.  
  2620. EoPS    Brian W. Kernighan and P.J. Plauger, The Elements of Programming
  2621.     Style, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5.
  2622.  
  2623. K&R I    Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  2624.     Language, Prentice Hall, 1978, ISBN 0-13-110163-3.
  2625.  
  2626. K&R II    Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  2627.     Language, Second Edition, Prentice Hall, 1988,
  2628.     ISBN 0-13-110362-8, 0-13-110370-9.
  2629.  
  2630. CT&P    Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989,
  2631.     ISBN 0-201-17928-8.
  2632.  
  2633.     P.J. Plauger, The Standard C Library, Prentice Hall, 1992,
  2634.     ISBN 0-13-131509-9.
  2635.  
  2636.     H. Rabinowitz and Chaim Schaap, Portable C, Prentice-Hall, 1990.
  2637.  
  2638. TNHD    Eric Raymond, Ed., The New Hacker's Dictionary, MIT Press, 1991,
  2639.     ISBN 0-262-68069-6.
  2640.  
  2641. There is a more extensive bibliography in the revised Indian Hill style
  2642. guide (see question 15.3).
  2643.  
  2644.  
  2645. Acknowledgements
  2646.  
  2647. Thanks to Jamshid Afshar, Sudheer Apte, Dan Bernstein, Stan Brown, Joe
  2648. Buehler, Burkhard Burow, Raymond Chen, Christopher Calabrese, James
  2649. Davies, Norm Diamond, Ray Dunn, Stephen M. Dunn, Bjorn Engsig, Dave
  2650. Gillespie, Samuel Goldstein, Ron Guilmette, Doug Gwyn, Tony Hansen, Joe
  2651. Harrington, Guy Harris, Jos Horsmeier, Blair Houghton, Kirk Johnson,
  2652. Peter Klausler, Andrew Koenig, John Lauro, Don Libes, Christopher Lott,
  2653. Tim McDaniel, Evan Manning, Mark Moraes, Darren Morby, Hans Olsson,
  2654. Francois Pinard, randall@virginia, Pat Rankin, Rich Salz, Chip
  2655. Salzenberg, Paul Sand, Doug Schmidt, Patricia Shanahan, Peter da Silva,
  2656. Joshua Simons, Henry Spencer, Erik Talvola, Clarke Thatcher, Chris
  2657. Torek, Goran Uddeborg, Wietse Venema, Ed Vielmetti, Larry Virden, Freek
  2658. Wiedijk, and Dave Wolverton, who have contributed, directly or
  2659. indirectly, to this article.  Special thanks to Karl Heuer, and
  2660. particularly to Mark Brader, who (to borrow a line from Steve Johnson)
  2661. have goaded me beyond my inclination, and occasionally beyond my
  2662. endurance, in relentless pursuit of a better FAQ list.
  2663.  
  2664.                     Steve Summit
  2665.                     scs@adam.mit.edu
  2666.                     scs%adam.mit.edu@mit.edu
  2667.                     mit-eddie!adam.mit.edu!scs
  2668.  
  2669. This article is Copyright 1988, 1990-1992 by Steve Summit.
  2670. It may be freely redistributed so long as the author's name, and this
  2671. notice, are retained.
  2672. The C code in this article (vstrcat(), error(), etc.) is public domain
  2673. and may be used without restriction.
  2674.