home *** CD-ROM | disk | FTP | other *** search
/ Nebula 1994 June / NEBULA_SE.ISO / Documents / FAQ / C-Language-faq / C-language.faq < prev   
Encoding:
Text File  |  1993-08-02  |  121.6 KB  |  3,226 lines

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