scs@adam.mit.edu (Steve Summit) (08/03/90)
In article <1990Aug1.042116.20244@athena.mit.edu> I wrote: >A: It is usually best to allocate an array of pointers, and then > initialize each pointer to a dynamically-allocated "row." > > int **array = (int **)malloc(nrows * ncolumns * sizeof(int *)); > for(i = 0; i < nrows; i++) > array[i] = (int *)malloc(ncolumns * sizeof(int)); This code wastes space and is misleading. The initial "dope vector" need only contain a pointer for each row of the intended array, not each element: int **array = (int **)malloc(nrows * sizeof(int *)); The same problem afflicts the second posted 2D allocation example, as well. Thanks to Freek Wiedijk for pointing this out. Steve Summit scs@adam.mit.edu
scs@adam.mit.edu (Steve Summit) (09/15/90)
This article contains minimal answers to the comp.lang.c frequently asked questions list. Please see the long version (posted on the first of each month) for more detailed explanations. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 5.3 p. 91; ANSI X3.159-1989 Sec. 3.2.2.3 . 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic functions) a constant 0 with an appropriate explicit cast is required. References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI X3.159- 1989 Sec. 3.2.2.3 . 3. But aren't pointers the same as ints? A: Not since the early days. References: K&R I Sec. 5.6 pp. 102-3; ANSI X3.159-1989 Sec. 3.3.4 . 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0) which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 13.1 p. 283; ANSI X3.159-1989 Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38, Rationale Sec. 4.1.5 p. 74. 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI X3.159-1989 Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and 3.6.5 . 8. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. References: K&R II Sec. 5.4 p. 102. 9. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 10. But I once used a compiler that wouldn't work unless NULL was used. A: This compiler was broken. 11. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). 12. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The fact that a preprocessor macro (NULL) is often used suggests that this is done because the value might change later, or on some weird machine. 13. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used in function calls." Arrays and Pointers 14. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. Use extern char a[]. 15. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. Otherwise, the two forms are not interchangeable. References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96; ANSI X3.159-1989 Sec. 3.5.4.3, Sec. 3.7.1 . 16. So what is meant by the "equivalence of pointers and arrays" in C? A: Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the fact that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec. 5.4.1 p. 93; ANSI X3.159-1989 Sec. 3.3.2.1, Sec. 3.3.6 . 17. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 18. How do I declare a pointer to an array? A: Usually, you don't want one. Think about using a pointer to one of the array's elements instead. 19. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Order of Evaluation 20. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++); " prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI X3.159-1989 Sec. 3.3 . 21. But what about the &&, ||, ?:, and comma operators? A: There is a special exception for those operators; left-to-right evaluation is guaranteed. References: ANSI X3.159-1989 Secs. 3.3.2.2, 3.3.13, 3.3.14, 3.3.15 . ANSI C 22. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long and arduous process, this C standard was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. 23. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for full addresses. 24. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. See the full list for details. 25. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed either by using new-style syntax consistently, or by changing the new-style prototype declaration to match the old-style definition. References: ANSI X3.159-1989 Sec. 3.3.2.2 . C Preprocessor 26. How can I write a macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 27. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes and no newlines inside quotes. 28. How can I write a cpp macro which takes a variable number of arguments? One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the compiler to indicate a single argument: #define DEBUG(args) {printf("DEBUG: ");printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Variable-Length Argument Lists 29. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4 pp. 286-9; ANSI X3.159-1989 Secs. 4.8 through 4.8.1.3 . 30. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12 p. 337; ANSI X3.159-1989 Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 . 31. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 32. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 33. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Memory Allocation 34. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 35. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 36. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. It cannot be used in programs which must be widely portable. Structures 37. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI X3.159-1989 Secs. 3.1.2.5, 3.2.2.1, 3.3.16 . 38. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 39. I have a program which works correctly, but it dumps core after it finishes. Why? A: Check to see if a structure declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. 40. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103. 41. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. References: ANSI X3.159-1989 Sec. 4.1.5 . 42. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Declarations 43. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec. 5.6.1 p. 102; ANSI X3.159-1989 Sec. 3.5.2.3 . 44. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. References: H&S Sec. 5.6.1 p. 102; ANSI X3.159-1989 Sec. 3.5.2.3 . 45. How do I declare a pointer to a function returning a pointer to a double? A: double *(*p)(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. References: H&S Sec. 5.10.1 p. 116. 46. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. Boolean Expressions and Variables 47. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 48. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI X3.159-1989 Secs. 3.3.3.3, 3.3.8, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5 . 49. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enums are compatible with ints. References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5 p. 100; ANSI X3.159-1989 Secs. 3.1.2.5, 3.5.2, 3.5.2.2 . Operating System Dependencies 50. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 51. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 52. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 53. How can a process change an environment variable in its caller? A: In general, it cannot. Stdio 54. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 55. My program's prompts and intermediate output don't always show up on my screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. 56. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 57. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Miscellaneous 58. Can someone tell me how to write itoa? A: Just use sprintf. 59. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI X3.159-1989 Sec. 4.12.2.3 . 60. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 61. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 62. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups. 63. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 64. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 65. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C and Ritchie's original pdp11 compiler, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 66. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 67. Where can I get a YACC grammar for C? A: See the unabridged list. 68. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. 69. Where can I get extra copies of this list? A: For now, just pull it off the net; it is normally posted on about the first of the month, with an Expiration: line which should keep it around all month. Thanks to Mark Brader, Joe Buehler, Christopher Calabrese, Stephen M. Dunn, Tony Hansen, Guy Harris, Karl Heuer, Blair Houghton, Kirk Johnson, Andrew Koenig, John Lauro, Christopher Lott, Rich Salz, Joshua Simons, and Erik Talvola, who have contributed, directly or indirectly, to this article. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (10/01/90)
Certain topics come up again and again on this newsgroup. They are good questions, and the answers may not be immediately obvious, but each time they recur, much net bandwidth and reader time is wasted on repetitive responses, and on tedious corrections to the incorrect answers which are inevitably posted. This article, which will be reposted periodically, attempts to answer these common questions definitively and succinctly, so that net discussion can move on to more constructive topics without continual regression to first principles. This article does not, and cannot, provide an exhaustive discussion of all of the subtle points and counterarguments which could be mentioned with respect to these topics. Cross-references to standard C publications have been provided, for further study by the interested and dedicated reader. A few of the more perplexing and pervasive topics may be further explored in some in-depth minitreatises posted in conjunction with this article. No mere newsgroup article can substitute for thoughtful perusal of a full-length language reference manual. Anyone interested enough in C to be following this newsgroup should also be interested enough to read and study one or more such manuals, preferably several times. Some vendors' compiler manuals are unfortunately inadequate; a few even perpetuate some of the myths which this article attempts to debunk. Two invaluable references, which are an excellent addition to any serious programmer's library, are: The C Programming Language, by Brian W. Kernighan and Dennis M. Ritchie. C: A Reference Manual, by Samuel P. Harbison and Guy L. Steele, Jr. Both exist in several editions. Andrew Koenig's book _C Traps and Pitfalls_ also covers many of the difficulties frequently discussed here. If you have a question about C which is not answered in this article, please try to answer it by referring to these or other books, or to knowledgeable colleagues, before posing your question to the net at large. There are many people on the net who are happy to answer questions, but the volume of repetitive answers posted to one question, as well as the growing numbers of questions as the net attracts more readers, can become oppressive. If you have questions or comments prompted by this article, please reply by mail rather than following up -- this article is meant to decrease net traffic, not increase it. This article is always being improved. Your input is welcomed. Send your comments to scs@adam.mit.edu and/or scs%adam.mit.edu@mit.edu; this article's From: line may be unuseable. Herewith, some frequently-asked questions and their answers: Null Pointers 1. What is this infamous null pointer, anyway? A: The language definition states that for each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. That is, the address-of operator & will never "return" a null pointer, nor will a successful call to malloc. (malloc returns a null pointer when it fails, and this is a typical use of null pointers: as a "special" pointer value with some other meaning, usually "not allocated" or "not pointing anywhere yet.") A null pointer is different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere (that is, at some random object, or at a garbage or unallocated address). See also question 34. As mentioned in the definition above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different. Although programmers need not know the internal values, the compiler must always be informed which null pointer is required, so it can make the distinction if necessary (see below). References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 5.3 p. 91; ANSI X3.159-1989 Sec. 3.2.2.3 . 2. How do I "get" a null pointer in my programs? A: According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal: char *p = 0; if(p != 0) However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. For instance, the Unix system call "execl" takes a variable-length, null pointer- terminated list of character pointer arguments. To generate a null pointer in a function call context, an explicit cast is typically required: execl("/bin/sh", "sh", "-c", "ls", (char *)0); If the (char *) cast were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong.) When function prototypes are in scope, argument passing becomes an "assignment context," and casts may safely be omitted, since the prototype tells the compiler that a pointer is required, and of which type, enabling it to correctly cast unadorned 0's. Function prototypes cannot provide the types for variable arguments in variable-length argument lists, however, so explicit casts are still required for those arguments. It is safest always to cast null pointer function arguments, to guard against varargs functions or those without prototypes, to allow interim use of non-ANSI compilers, and to demonstrate that you know what you are doing. Summary: unadorned 0 okay: explicit cast required: initialization function call, no prototype in scope assignments variable argument to comparisons varargs function function call, prototype in scope, fixed argument References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI X3.159- 1989 Sec. 3.2.2.3 . 3. But aren't pointers the same as ints? A: Not since the early days. Attempting to push pointers into integers, or build pointers out of integers, has always been machine-dependent and unportable, and doing so is strongly discouraged. (Any object pointer may be cast to the "universal" pointer type void *, or char * under a pre-ANSI compiler, when heterogeneous pointers must be passed around.) References: K&R I Sec. 5.6 pp. 102-3; ANSI X3.159-1989 Sec. 3.3.4 . 4. What is NULL and how is it #defined? A: As a stylistic convention, many people prefer not to have unadorned 0's scattered throughout their programs. For this reason, the preprocessor macro NULL is #defined (by stdio.h or stddef.h), with value 0 (or (void *)0, about which more later). A programmer who wishes to make explicit the distinction between 0 the integer and 0 the null pointer can then use NULL whenever a null pointer is required. This is a stylistic convention only; the preprocessor turns NULL back to 0 which is then recognized by the compiler (in pointer contexts) as before. In particular, a cast may still be necessary before NULL (as before 0) in a function call argument. (The table under question 2 above applies for NULL as well as 0.) NULL should _only_ be used for pointers. It should not be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (ANSI allows the #definition of NULL to be (void *)0, which will not work in non- pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition #define NUL '\0' if you must. References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 13.1 p. 283; ANSI X3.159-1989 Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38, Rationale Sec. 4.1.5 p. 74. 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: Programmers should never need to know the internal representation(s) of null pointers, because they are normally taken care of by the compiler. If a machine uses a nonzero bit pattern for null pointers, it is the compiler's responsibility to generate it when the programmer requests, by writing "0" or "NULL," a null pointer. Therefore #defining NULL as 0 on a machine for which internal null pointers are nonzero is as valid as on any other, because the compiler must (and can) still generate the machine's correct null pointers in response to unadorned 0's seen in pointer contexts. 6. If NULL were defined as follows: #define NULL (char *)0 wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. The suggested #definition would make uncast NULL arguments to functions expecting pointers to characters to work correctly, but pointer arguments to other types would still be problematical, and legal constructions such as FILE *fp = NULL; could fail. Nevertheless, ANSI C allows the alternate #define NULL (void *)0 definition for NULL. Besides helping incorrect programs to work (but only on machines with all pointers the same, thus questionably valid assistance) this definition may catch programs which use NULL incorrectly (e.g. when the ASCII nul character was really intended). 7. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: When C requires the boolean value of an expression (in the if, while, for, and do statements, and with the &&, ||, !, and ?: operators), a false value is produced when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes if(expr) where "expr" is any expression at all, the compiler essentially acts as if it had been written as if(expr != 0) Substituting the trivial pointer expression "p" for "expr," we have if(p) is equivalent to if(p != 0) and this is a comparison context, so the compiler can tell that the (implicit) 0 is a null pointer, and use the correct value. There is no trickery involved here; compilers do work this way, and generate identical code for both statements. The internal representation of a pointer does not matter. The boolean negation operator, !, can be described as follows: !expr is essentially equivalent to expr?0:1 It is left as an exercise for the reader to show that if(!p) is equivalent to if(p == 0) See also question 48. References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI X3.159-1989 Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and 3.6.5 . 8. If "NULL" and "0" are equivalent, which should I use? A: Many programmers believe that "NULL" should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding "NULL" and "0" is only compounded by hiding "0" behind a #definition, and prefer to use unadorned "0" instead. There is no one right answer. C programmers must understand that "NULL" and "0" are interchangeable and that an uncast "0" is perfectly acceptable in initialization, assignment, and comparison contexts. Any usage of "NULL" (as opposed to "0") should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's. Again, NULL should not be used for other than pointers. References: K&R II Sec. 5.4 p. 102. 9. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. Although preprocessor macros are often used in place of numbers because the numbers might change, this is _not_ the reason that NULL is used in place of 0. The language guarantees that source-code 0's (in pointer contexts) generate null pointers. NULL is used only as a stylistic convention. 10. But I once used a compiler that wouldn't work unless NULL was used. A: This compiler was broken. In general, making decisions about a language based on the behavior of one particular compiler is likely to be counterproductive. 11. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. (On some machines the internal value is 0; on others it is not.) A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). When the term "null" or "NULL" is casually used, one of several things may be meant: 1. The conceptual null pointer, the abstract language concept defined in question 1. It is implemented with... 2. The internal (or run-time) representation of a null pointer, which may be different for different pointer types. The actual values should be of concern only to compiler writers. Authors of C programs never see them, since they use... 3. The source code syntax for null pointers, which is the single character "0". It is often hidden behind... 4. The NULL macro, which is #defined to be "0" or "(void *)0". Finally, as a red herring, we have 5. The ASCII null character (NUL), which does have all bits zero, but has no relation to the null pointer except in name. This article always uses the phrase "null pointer" for sense 1, the character "0" for sense 3, and the capitalized word "NULL" for sense 4. 12. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: C programmers traditionally like to know more than they need to about the underlying machine implementation. The construct "if(p == 0)" is easily misread as calling for conversion of p to an integral type, rather than 0 to a pointer type, before the comparison. The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The fact that a preprocessor macro (NULL) is often used suggests that this is done because the value might change later, or on some weird machine. Finally, the distinction between the several uses of the term "null" (listed above) is often overlooked. One good way to wade out of the confusion is to imagine that C had a keyword (perhaps "nil", like Pascal) with which null pointers were requested. The compiler could either turn "nil" into the correct type of null pointer, when it could determine the type from the source code (as it does with 0's in reality), or complain when it could not. Now, in fact, in C the keyword for a null pointer is not "nil" but "0", which works almost as well, except that an uncast "0" in a non-pointer context generates an integer zero. If the null pointer keyword were "nil" the compiler could emit an error message for an ambiguous usage, but since it is "0" the compiler may end up emitting incorrect code. 13. I'm still confused. I just can't understand all this null pointer stuff. A: Follow these two simple rules: 1. When you want to refer to a null pointer in source code, use "0" or "NULL". 2. If the usage of "0" or "NULL" is in a function call, cast it to the pointer type expected by the function being called. The rest of the discussion has to do with other people's misunderstandings, or with the internal representation of null pointers, which you shouldn't need to know. Arrays and Pointers 14. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. The type "pointer-to-type-T" is not the same as "array-of-type-T." Use extern char a[]. 15. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. This identity is related to the fact that arrays "turn into" pointers in expressions. That is, when an array name is mentioned in an expression, it is converted immediately into a pointer to the array's first element. Therefore, an array is never passed to a function; rather a pointer to its first element is passed instead. Allowing pointer parameters to be declared as arrays is a simply a way of making it look as though the array was actually being passed. Some programmers prefer, as a matter of style, to use this syntax to indicate that the pointer parameter is expected to point to the start of an array rather than to a single value. Since functions can never receive arrays as parameters, any parameter declarations which "look like" arrays, e.g. f(a) char a[]; are treated as if they were pointers, since that is what the function will receive if an array is passed: f(a) char *a; To repeat, however, this conversion holds only within function formal parameter declarations, nowhere else. If this conversion confuses you, don't use it; many people have concluded that the confusion it causes outweighs the small advantage of having the declaration "look like" the call and/or the uses within the function. References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96; ANSI X3.159-1989 Sec. 3.5.4.3, Sec. 3.7.1 . 16. So what is meant by the "equivalence of pointers and arrays" in C? A: Perhaps no aspect of C is more confusing than pointers, and the confusion is compounded by statements like the one above. Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. (The fact that, as formal parameters to functions, array-style and pointer-style declarations are in fact interchangeable does nothing to reduce the confusion.) "Equivalence" refers to the fact (mentioned above) that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. That is, if we have char a[10]; char *p; int i; we can refer to a[i] and p[i]. (That pointers can be subscripted like arrays is hardly surprising, since arrays have decayed into pointers by the time they are subscripted.) References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec. 5.4.1 p. 93; ANSI X3.159-1989 Sec. 3.3.2.1, Sec. 3.3.6 . 17. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays are confusing, and it is best to avoid them. (The confusion is heightened by incorrect compilers, including some versions of pcc and pcc-derived lint's, which incorrectly accept assignments of multi-dimensional arrays to multi-level pointers.) If you are passing a two-dimensional array to a function: int array[YSIZE][XSIZE]; f(array); the function's declaration should match: f(int a[][XSIZE]) {...} or f(int (*a)[XSIZE]) {...} In the first declaration, the compiler performs the usual implicit rewriting of "array of array" to "pointer to array;" in the second form the pointer declaration is explicit. The called function does not care how big the array is, but it must know its shape, so the "column" dimension XSIZE must be included. In both cases the number of "rows" is irrelevant, and omitted. If a function is already declared as accepting a pointer to a pointer, an intermediate pointer would need to be used when attempting to call it with a two-dimensional array: int *ip = &a[0][0]; g(&ip); ... g(int **ipp) {...} Note that this usage is liable to be misleading (if not incorrect), since the array has been "flattened" (its shape has been lost). 18. How do I declare a pointer to an array? A: Usually, you don't want one. Think about using a pointer to one of the array's elements instead. Arrays of type T decay into pointers to type T, which is convenient; subscripting or incrementing the resultant pointer accesses the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally only useful when operating on multidimensional arrays. (See the question above.) 19. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." The resulting "ragged" array often saves space, although it may not be contiguous in memory as a real array would be. int **array = (int **)malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array[i] = (int *)malloc(ncolumns * sizeof(int)); (In "real" code, of course, malloc's return value should be checked.) You can keep the array's contents contiguous, while losing the ability to have rows of varying and different lengths, with a bit of explicit pointer arithmetic: int **array = (int **)malloc(nrows * sizeof(int *)); array[0] = (int *)malloc(nrows * ncolumns * sizeof(int)); for(i = 1; i < nrows; i++) array[i] = array[0] + i * ncolumns; In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: array[i][j]. If the double indirection implied by the above scheme is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array: int *array = (int *)malloc(nrows * ncolumns * sizeof(int)); However, you must now perform subscript calculations manually, accessing array[i, j] with array[i * ncolumns + j]. (A macro can hide the explicit calculation, but invoking it then requires parentheses and commas which don't look exactly like multidimensional array subscripts.) Order of Evaluation 20. Under my compiler, the code int i = 7; printf("%d\n", i++ * i++); prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: Although the postincrement and postdecrement operators ++ and -- perform the operations after yielding the former value, many people misunderstand the implication of "after." It is _not_ guaranteed that the operation is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered "finished" (before the next "sequence point," in ANSI C's terminology). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards. The order of other embedded side effects is similarly undefined. For example, the expression i + (i = 2) may or may not have the value 4. ANSI allows compilers to reject code which contains such ambiguous or undefined side effects. References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI X3.159-1989 Sec. 3.3 . 21. But what about the &&, ||, ?:, and comma operators? I see code like "if((c = getchar()) == EOF || c == '\n')" ... A: There is a special exception for those operators; each of them does imply a sequence point (i.e. left-to-right evaluation is guaranteed). References: ANSI X3.159-1989 Secs. 3.3.2.2, 3.3.13, 3.3.14, 3.3.15 . ANSI C 22. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long and arduous process, this C standard was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardizes existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the much-lambasted trigraph sequences for transfer of source code between machines with deficient or multinational character sets). The ANSI C standard also formalizes the C run-time library support routines, an unprecedented effort. 23. How can I get a copy of the ANSI C standard? A: Copies are available from American National Standards Institute 1430 Broadway New York, NY 10018 (212) 642-4900 or Global Engineering Documents 2805 McGaw Avenue Irvine, CA 92714 (714) 261-1455 The cost is approximately $50.00, plus $6.00 shipping. Quantity discounts are available. 24. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. Check your nearest comp.sources archive. (See also questions 61 and 62.) 25. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style declaration "extern int func(float);" with the old-style definition "int func(x) float x;". Old C (and ANSI C, in the absence of prototypes) silently promotes floats to doubles when passing them as arguments, and makes a corresponding silent change to formal parameter declarations, so the old-style definition actually says that func takes a double. The problem can be fixed either by using new-style syntax consistently in the definition: int func(float x) { ... } or by changing the new-style prototype declaration to match the old-style definition: extern int func(double); (In this case, it would be clearest to change the old-style definition to use double as well). References: ANSI X3.159-1989 Sec. 3.3.2.2 . C Preprocessor 26. How can I write a macro to swap two values? A: There is no good answer to this question. If the values are integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers. If the macro is intended to be used on values of arbitrary type (the usual goal), it cannot use a temporary, since it doesn't know what type of temporary it needs, and standard C does not provide a typeof operator. (GNU C does.) The best all-around solution is probably to forget about using a macro. If you're worried about the use of an ugly temporary, and know that your machine provides an exchange instruction, convince your compiler vendor to recognize the standard three-assignment swap idiom in the optimization phase. Alternatively, use a language which supports multiple, parallel assignment (a,b := b,a). 27. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (note particularly that an apostrophe within a contracted word looks like the beginning of a character constant) and no newlines inside quotes. Therefore, natural-language comments should always be written between the "official" comment delimiters /* and */. 28. How can I write a cpp macro which takes a variable number of arguments? One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the compiler to indicate a single argument: #define DEBUG(args) {printf("DEBUG: ");printf args;} if(n != 0) DEBUG(("n is %d\n", n)); The obvious disadvantage to this trick is that the caller must always remember to use the extra parentheses. (It is often best to use a bona-fide function, which can take a variable number of arguments in a well-defined way, rather than a macro. See questions 29 and 30 below.) Variable-Length Argument Lists 29. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. Here is a function which concatenates an arbitrary number of strings into malloc'ed memory, using stdarg: #include <stddef.h> /* for NULL */ #include <stdarg.h> /* for va_ stuff */ #include <string.h> /* for strcat et al */ #include <stdlib.h> /* for malloc */ extern char *malloc(); /* redundant */ /* VARARGS1 */ char * vstrcat(char *first, ...) { int len = 0; char *retbuf; va_list argp; char *p; if(first == NULL) return NULL; len = strlen(first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) len += strlen(p); va_end(argp); retbuf = malloc(len + 1); /* +1 for trailing \0 */ if(retbuf == NULL) return NULL; (void)strcpy(retbuf, first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) (void)strcat(retbuf, p); va_end(argp); return retbuf; } Usage is something like char *str = vstrcat("Hello, ", "world!", (char *)NULL); Note the cast on the last argument. (Also note that the caller must free the returned, malloc'ed storage.) Using the older varargs package, rather than stdarg, requires a few changes which are not discussed here, in the interests of brevity. See the next question for hints. References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4 pp. 286-9; ANSI X3.159-1989 Secs. 4.8 through 4.8.1.3 . 30. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. Here is an "error" routine which prints an error message, preceded by the string "error: " and terminated with a newline: #include <stdio.h> #include <stdarg.h> void error(char *fmt, ...) { va_list argp; fprintf(stderr, "error: "); va_start(argp, fmt); vfprintf(stderr, fmt, argp); va_end(argp); fprintf(stderr, "\n"); } To use varargs, instead of stdarg, change the function header to: void error(va_alist) va_dcl { char *fmt; change the va_start line to va_start(argp); and add the line fmt = va_arg(argp, char *); between the calls to va_start and vfprintf. (Note that there is no semicolon after va_dcl.) References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12 p. 337; ANSI X3.159-1989 Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 . 31. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. You're on your own. 32. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Some systems have a nonstandard nargs() function available, but its use is questionable, since it typically returns the number of words pushed, not the number of arguments. (Floating point values and structures are usually passed as several words.) Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. printf-like functions do this by looking for formatting specifiers (%d and the like) in the format string (which is why these functions fail badly if the format string does not match the argument list). Another common technique (useful when the arguments are all of the same type) is to use a sentinel value (often 0, -1, or an appropriately-cast null pointer) at the end of the list (see the vstrcat and execl examples under questions 29 and 2 above). 33. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. You must provide a version of that other function which accepts a va_list pointer, as does vfprintf in the example above. If the arguments must be passed directly as actual arguments (not indirectly through a va_list pointer) to another function which is itself variadic (for which you do not have the option of creating an alternate, va_list-accepting version) no portable solution is possible. (The problem can often be solved by resorting to machine-specific assembly language.) Memory Allocation 34. Why doesn't this program work? main() { char *answer; printf("Type something:\n"); gets(answer); printf("You typed \"%s\"\n", answer); } A: The pointer variable "answer," which is handed to the gets function as the location into which the response should be stored, has not been set to point to any valid storage. It is an uninitialized variable, just as is the variable i in this example: main() { int i; printf("i = %d\n", i); } That is, we cannot say where the pointer "answer" points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that "answer" starts out as a null pointer.) The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation: #include <stdio.h> main() { char answer[100]; printf("Type something:\n"); fgets(answer, 100, stdin); printf("You typed \"%s\"\n", answer); } Note that this example also uses fgets instead of gets (always a good idea), so that the size of the array can be specified, so that fgets will not overwrite the end of the array if the user types an overly-long line. (Unfortunately, gets and fgets differ in their treatment of the trailing \n.) It would also be possible to use malloc to allocate the answer buffer, and/or to parameterize its size (#define ANSWERSIZE 100). 35. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages for malloc stated that the contents of freed memory was "left undisturbed;" this ill-advised guarantee is not universal and is not required by ANSI. Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list: struct list *listp, *nextp; for(listp = base; listp != NULL; listp = nextp) { nextp = listp->next; free((char *)listp); } and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer. 36. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context. alloca cannot be written portably, and is difficult to implement on machines without a stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), stdin, 100). For these reasons, alloca cannot be used in programs which must be widely portable, no matter how useful it might be. Structures 37. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: What K&R I said was that the restrictions on struct operations would be lifted in a forthcoming version of the compiler, and in fact struct assignment and passing were fully functional in Ritchie's compiler even as K&R I was being published. Although a few early C compilers lacked struct assignment, all modern compilers support it, and it is part of the ANSI C standard, so there should be no reluctance to use it. References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI X3.159-1989 Secs. 3.1.2.5, 3.2.2.1, 3.3.16 . 38. How does struct passing and returning work? A: When structures are passed as arguments to functions, the entire struct is pushed on the stack, which may involve significant overhead for large structures. It may be preferable in such cases to pass a pointer to the structure instead. Structures are returned from functions either in a special, static place (which may make struct-valued functions nonreentrant) or in a location pointed to by an extra, "hidden" argument to the function. 39. The following program works correctly, but it dumps core after it finishes. Why? struct list { char *item; struct list *next; } /* Here is the main program. */ main(argc, argv) ... A: A missing semicolon causes the compiler to believe that main returns a struct list. (The connection is hard to see because of the intervening comment.) When struct-valued functions are implemented by adding a hidden return pointer, the generated code tries to store a struct with respect to a pointer which was not actually passed (in this case, by the C start-up code). Attempting to store a structure into memory pointed to by the argc or argv value on the stack (where the compiler expected to find the hidden return pointer) causes the core dump. 40. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. A byte- by-byte comparison could be invalidated by random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison would require unacceptable amounts of repetitive, in-line code for large structures. Either method would not necessarily "do the right thing" with pointer fields: oftentimes, equality should be judged by equality of the things pointed to rather than strict equality of the pointers themselves. If you want to compare two structures, you must write your own function to do so. C++ (among other languages) would let you arrange for the == operator to map to your function. References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103. 41. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. If you don't have it, a suggested implementation is #define offsetof(type, mem) ((size_t) \ ((char *)&((type *) 0)->mem - (char *)((type *) 0))) This implementation is not 100% portable; some compilers may legitimately refuse to accept it. See the next question for a usage hint. References: ANSI X3.159-1989 Sec. 4.1.5 . 42. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is offsetof(struct a, b) If structp is a pointer to an instance of this structure, and b is an int field with offset as computed above, b's value can be set indirectly with *(int *)((char *)structp + offset) = value; Declarations 43. I can't seem to define a linked list node which contains a pointer to itself. I tried typedef struct { char *item; NODEPTR next; } NODE, *NODEPTR; but the compiler gave me error messages. Can't a struct in C contain a pointer to itself? A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. The problem is that the example above attempts to hide the struct pointer behind a typedef, which is not complete at the time it is used. First, rewrite it without a typedef: struct node { char *item; struct node *next; }; Then, if you feel you must use typedefs, define them after the fact: typedef struct node NODE, *NODEPTR; Alternatively, define the typedefs first (using the line just above) and follow it with the full definition of struct node, which can then use the NODEPTR typedef for the "next" field. References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec. 5.6.1 p. 102; ANSI X3.159-1989 Sec. 3.5.2.3 . 44. How can I define a pair of mutually referential structures? I tried typedef struct { int structafield; STRUCTB *bpointer; } STRUCTA; typedef struct { int structbfield; STRUCTA *apointer; } STRUCTB; but the compiler doesn't know about STRUCTB when it is used in struct a. A: Again, the problem is not the pointers but the typedefs. First, define the two structures without using typedefs: struct a { int structafield; struct b *bpointer; }; struct b { int structbfield; struct a *apointer; }; The compiler can accept the field declaration struct b *bpointer within struct a, even though it has not yet heard of struct b. Occasionally it is necessary to precede this couplet with the empty declaration struct b; to mask the declaration (if in an inner scope) from a different struct b in an outer scope. Again, the typedefs could also be defined before, and then used within, the definitions for struct a and struct b. Problems arise only when an attempt is made to define and use a typedef within the same declaration. References: H&S Sec. 5.6.1 p. 102; ANSI X3.159-1989 Sec. 3.5.2.3 . 45. How do I declare a pointer to a function returning a pointer to a double? A: There are at least three answers to this question: 1. double *(*p)(); 2. Build it up in stages, using typedefs: typedef double *pd; /* pointer to double */ typedef pd fpd(); /* func returning ptr to double */ typedef fpd *pfpd; /* ptr to func ret ptr to double */ pfpd p; 3. Use the cdecl program, which turns English into C and vice versa: $ cdecl cdecl> declare p as pointer to function returning pointer to double double *(*p)(); cdecl> cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions). References: H&S Sec. 5.10.1 p. 116. 46. So where can I get cdecl? A: Several public-domain versions are available. One is in volume 14 of comp.sources.unix . (Commercial versions may also be available, at least one of which was shamelessly lifted from the public domain copy submitted by Graham Ross, one of cdecl's originators.) Boolean Expressions and Variables 47. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. (Using an int for a boolean may be faster, while using char will probably save data space.) The choice between #defines and enums is arbitrary and not terribly interesting. Use any of #define TRUE 1 #define YES 1 #define FALSE 0 #define NO 0 enum bool {false, true}; enum bool {no, yes}; as long as you are consistent within one program or project. (The enum may be preferable if your debugger expands enum values when examining variables.) Some people prefer variants like #define TRUE (1==1) #define FALSE (!TRUE) These don't buy anything (see below). 48. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test if((a == b) == TRUE) will succeed (if a, in fact, equals b and TRUE is one), but this code is obviously silly. In general, explicit tests against TRUE and FALSE are undesirable, because some library functions (notably isupper, isalpha, etc.) return, on success, a nonzero value which is _not_ necessarily 1. A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable or as the return value from a Boolean function, never in a comparison. Preprocessor macros like TRUE and FALSE (and, in fact, NULL) are used for code readability, not because the underlying values might ever change. That "true" is 1 and "false" (and source-code null pointers) 0 is guaranteed by the language. (See also question 7.) References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI X3.159-1989 Secs. 3.3.3.3, 3.3.8, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5 . 49. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. Although many people might have wished otherwise, the ANSI standard says that enums may be freely intermixed with integral types, without errors. (If such intermixing were disallowed without explicit casts, judicious use of enums could catch certain programming errors.) The advantages of enums are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enum variables are examined, and that a compiler may generate nonfatal warnings when enums and ints are indiscriminately mixed (such mixing can still be considered bad style even though it is not strictly illegal) or when enum cases are left out of switch statements. References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5 p. 100; ANSI X3.159-1989 Secs. 3.1.2.5, 3.5.2, 3.5.2.2 . Operating System Dependencies 50. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. The delivery of characters from a "keyboard" to a C program is a function of the operating system, and cannot be standardized by the C language. If you are using curses, use its cbreak() function. Under UNIX, use ioctl to play with the terminal driver modes (CBREAK or RAW under "classic" versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or Posix systems). Under MS-DOS, use getch(). Under other operating systems, you're on your own. Beware that some operating systems make this sort of thing impossible, because character collection into input lines is done by peripheral processors not under direct control of the CPU running your program. Operating system specific questions are not appropriate for comp.lang.c . Several common questions are answered in frequently- asked questions postings in the comp.unix.questions and comp.sys.ibm.pc newsgroups. 51. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. Depending on your system, you may be able to use "nonblocking I/O", or a system call named "select", or the FIONREAD ioctl, or O_NDELAY, or a kbhit() routine. 52. How can my program discover the complete pathname to the executable file from which it was invoked? A: Depending on the operating system, argv[0] may contain all or part of the pathname. (It may also contain nothing.) You may be able to duplicate the command language interpreter's search path logic to locate the executable if the name in argv[0] is incomplete. However, there is no guaranteed or portable solution. 53. How can a process change an environment variable in its caller? A: In general, it cannot. If the calling process is prepared to listen explicitly for some indication that its environment should be changed, a special-case scheme can be set up. (Under Unix, a child process cannot directly affect its parent at all. Other operating systems have different process environments which could intrinsically support such communication.) Stdio 54. Why does errno contain ENOTTY after a call to printf? A: Many implementations of the stdio package adjust their behavior slightly depending on whether stdout is a terminal or not. To make this determination, these implementations perform an operation which fails (with ENOTTY) if stdout is not a terminal. Although the output operation goes on to complete successfully, errno still contains ENOTTY. This behavior can be mildly confusing, but it is not strictly incorrect, because it is only meaningful for a program to inspect the contents of errno after an error has occurred (that is, after a library function that sets errno on error has returned an error code). 55. My program's prompts and intermediate output don't always show up on my screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. Several mechanisms attempt to perform the fflush for you, at the "right time," but they do not always work, particularly when stdout is a pipe rather than a terminal. 56. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. In particular, "\n" in a format string does not mean "expect a newline", it means "discard all whitespace". But the only way to discard all whitespace is to continue reading the stream until a non-whitespace character is seen (which is then left in the buffer for the next input), so the effect is that it keeps going until it sees a nonblank line. 57. So what should I use instead? A: You could use a "%c" format, which will read one character that you can then manually compare against a newline; or "%*c" and no variable if you're willing to trust the user to hit a newline; or "%*[^\n]%*c" to discard everything up to and including the newline. Or you could use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Miscellaneous 58. Can someone tell me how to write itoa (the inverse of atoi)? A: Just use sprintf. 59. I know that the library routine localtime will convert a time_t into a broken-down struct tm, and that ctime will convert a time_t to a printable string. How can I perform the inverse operations of converting a struct tm or a string into a time_t? A: ANSI C specifies a library routine, mktime, which converts a struct tm to a time_t. Several public-domain versions of this routine are available if your compiler does not support it yet. Converting a string to a time_t is harder, because of the wide variety of date and time formats which should be parsed. Public- domain routines have been written for performing this function, as well, but they are less likely to become standardized. References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI X3.159-1989 Sec. 4.12.2.3 . 60. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: Standard headers exist in part so that definitions appropriate to your compiler, operating system, and processor can be supplied. You cannot just pick up a copy of someone else's header file and expect it to work, unless that person uses exactly the same environment. Ask your vendor why the file was not provided (or to send another copy, if you've merely lost it). 61. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available: p2c written by Dave Gillespie, and posted to comp.sources.unix in March, 1990 (Volume 21). ptoc another comp.sources.unix contribution, this one written in Pascal (comp.sources.unix, Volume 10, also patches in Volume 13?). f2c jointly developed by people from Bell Labs, Bellcore, and Carnegie Mellon. To find about f2c, send the message "send index from f2c" to netlib@research.att.com or research!netlib. FOR_C Available from: Cobalt Blue 2940 Union Ave., Suite C San Jose, CA 95124 (408) 723-0474 Promula.Fortran Available from Promula Development Corp. 3620 N. High St., Suite 301 Columbus, OH 43214 (614) 263-5454 The comp.sources.unix archives also contain converters between "K&R" C and ANSI C. 62. Where can I get copies of all these public-domain programs? A: If you have access to Usenet, see the regular postings in the comp.sources.unix and comp.sources.misc newsgroups, which describe, in some detail, the archiving policies and how to retrieve copies. Otherwise, you can try anonymous ftp and/or uucp from a central, public-spirited site, such as uunet.uu.net, but this article cannot track or list all of the available sites and how to access them. 63. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? (And vice versa?) A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use, and may not be possible at all. Read your compiler documentation very carefully; sometimes there is a "mixed-language programming guide," although the techniques for passing arguments correctly are often arcane. 64. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good, mostly because of the possibility of accidentally leaving comments unclosed by including the characters "/*" within them. For this reason, it is usually better to "comment out" large sections of code, which might contain comments, with #ifdef or #if 0. The character sequences /* and */ are not special within double- quoted strings, and do not therefore introduce comments, because a program (particularly one which is generating C code as output) might want to print them. 65. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C and Ritchie's original pdp11 compiler, attempt to leave out floating point support if it looks like it will not be needed. In particular, the non- floating-point versions of printf and scanf save space by not including code to handle %e, %f, and %g. Occasionally the heuristics for "is the program using floating point?" are insufficient, and the programmer must insert one dummy explicit floating-point operation to force loading of floating-point support. Unfortunately, an apparently common sort of program (thus the frequency of the question) uses scanf to read, and/or printf to print, floating-point values upon which no arithmetic is done, which elicits the problem under Turbo C. In general, questions about a particular compiler are inappropriate for comp.lang.c . Problems with PC compilers, for instance, will find a more receptive audience in a PC newsgroup. 66. Does anyone have a C compiler test suite I can use? A: Plum Hall, (1 Spruce Ave., Cardiff, NJ 08232, USA), among others, sells one. 67. Where can I get a YACC grammar for C? A: Several grammars are floating around; keep your eyes open. There is one on uunet.uu.net (192.48.96.2) in net.sources/ansi.c.grammar.Z . FSF's GNU C compiler contains a grammar, as does the appendix to K&R II. Several have recently been posted to the net. 68. Where can I get the "Indian Hill Style Guide" and other coding standards? A: Various standards are available for anonymous ftp from: site file/directory cs.washington.edu ~ftp/pub/cstyle.tar.Z (128.95.1.4) cs.toronto.edu doc/programming giza.cis.ohio-state.edu pub/style-guide prep.ai.mit.edu pub/gnu/standards.text 69. Where can I get extra copies of this list? A: For now, just pull it off the net; it is normally posted on about the first of the month, with an Expiration: line which should keep it around all month. Eventually, it may be available for anonymous ftp, or via a mailserver. Thanks to Mark Brader, Joe Buehler, Christopher Calabrese, Stephen M. Dunn, Tony Hansen, Guy Harris, Karl Heuer, Blair Houghton, Kirk Johnson, Andrew Koenig, John Lauro, Christopher Lott, Rich Salz, Joshua Simons, and Erik Talvola, who have contributed, directly or indirectly, to this article. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained. The C code in this article (vstrcat, error, etc.) is public domain and may be used without restriction.
scs@adam.mit.edu (Steve Summit) (10/01/90)
This article contains minimal answers to the comp.lang.c frequently asked questions list. Please see the long version for more detailed explanations. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 5.3 p. 91; ANSI X3.159-1989 Sec. 3.2.2.3 . 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic functions) a constant 0 with an appropriate explicit cast is required. References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI X3.159- 1989 Sec. 3.2.2.3 . 3. But aren't pointers the same as ints? A: Not since the early days. References: K&R I Sec. 5.6 pp. 102-3; ANSI X3.159-1989 Sec. 3.3.4 . 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0) which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 13.1 p. 283; ANSI X3.159-1989 Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38, Rationale Sec. 4.1.5 p. 74. 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI X3.159-1989 Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and 3.6.5 . 8. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. References: K&R II Sec. 5.4 p. 102. 9. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 10. But I once used a compiler that wouldn't work unless NULL was used. A: This compiler was broken. 11. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). 12. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The fact that a preprocessor macro (NULL) is often used suggests that this is done because the value might change later, or on some weird machine. 13. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used in function calls." Arrays and Pointers 14. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. Use extern char a[]. 15. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. Otherwise, the two forms are not interchangeable. References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96; ANSI X3.159-1989 Sec. 3.5.4.3, Sec. 3.7.1 . 16. So what is meant by the "equivalence of pointers and arrays" in C? A: Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the fact that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec. 5.4.1 p. 93; ANSI X3.159-1989 Sec. 3.3.2.1, Sec. 3.3.6 . 17. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 18. How do I declare a pointer to an array? A: Usually, you don't want one. Think about using a pointer to one of the array's elements instead. 19. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Order of Evaluation 20. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++); " prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI X3.159-1989 Sec. 3.3 . 21. But what about the &&, ||, ?:, and comma operators? A: There is a special exception for those operators; left-to-right evaluation is guaranteed. References: ANSI X3.159-1989 Secs. 3.3.2.2, 3.3.13, 3.3.14, 3.3.15 . ANSI C 22. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long and arduous process, this C standard was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. 23. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for full addresses. 24. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. See the full list for details. 25. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed either by using new-style syntax consistently, or by changing the new-style prototype declaration to match the old-style definition. References: ANSI X3.159-1989 Sec. 3.3.2.2 . C Preprocessor 26. How can I write a macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 27. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes and no newlines inside quotes. 28. How can I write a cpp macro which takes a variable number of arguments? One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the compiler to indicate a single argument: #define DEBUG(args) {printf("DEBUG: ");printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Variable-Length Argument Lists 29. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4 pp. 286-9; ANSI X3.159-1989 Secs. 4.8 through 4.8.1.3 . 30. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12 p. 337; ANSI X3.159-1989 Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 . 31. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 32. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 33. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Memory Allocation 34. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 35. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 36. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. It cannot be used in programs which must be widely portable. Structures 37. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI X3.159-1989 Secs. 3.1.2.5, 3.2.2.1, 3.3.16 . 38. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 39. I have a program which works correctly, but it dumps core after it finishes. Why? A: Check to see if a structure declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. 40. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103. 41. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. References: ANSI X3.159-1989 Sec. 4.1.5 . 42. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Declarations 43. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec. 5.6.1 p. 102; ANSI X3.159-1989 Sec. 3.5.2.3 . 44. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. References: H&S Sec. 5.6.1 p. 102; ANSI X3.159-1989 Sec. 3.5.2.3 . 45. How do I declare a pointer to a function returning a pointer to a double? A: double *(*p)(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. References: H&S Sec. 5.10.1 p. 116. 46. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. Boolean Expressions and Variables 47. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 48. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI X3.159-1989 Secs. 3.3.3.3, 3.3.8, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5 . 49. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enums are compatible with ints. References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5 p. 100; ANSI X3.159-1989 Secs. 3.1.2.5, 3.5.2, 3.5.2.2 . Operating System Dependencies 50. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 51. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 52. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 53. How can a process change an environment variable in its caller? A: In general, it cannot. Stdio 54. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 55. My program's prompts and intermediate output don't always show up on my screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. 56. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 57. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Miscellaneous 58. Can someone tell me how to write itoa? A: Just use sprintf. 59. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI X3.159-1989 Sec. 4.12.2.3 . 60. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 61. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 62. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups. 63. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 64. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 65. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C and Ritchie's original pdp11 compiler, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 66. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 67. Where can I get a YACC grammar for C? A: See the unabridged list. 68. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. 69. Where can I get extra copies of this list? A: For now, just pull it off the net; it is normally posted on about the first of the month, with an Expiration: line which should keep it around all month. Thanks to Mark Brader, Joe Buehler, Christopher Calabrese, Stephen M. Dunn, Tony Hansen, Guy Harris, Karl Heuer, Blair Houghton, Kirk Johnson, Andrew Koenig, John Lauro, Christopher Lott, Rich Salz, Joshua Simons, and Erik Talvola, who have contributed, directly or indirectly, to this article. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
ray@vantage.UUCP (Ray Liere) (10/05/90)
First, my thanks to you for the effort you spend in putting out the FAQ document -- I keep a printout of the latest version handy with my other C references ... which brings me to a request ... if convenient, could a "date last revised" be put near the top? (That way I know whether or not I need to print it -- or perhaps my copy from last month is still current ...). Thanks again for your good and useful works! Ray Liere Vantage Consulting and Research Corporation voice: (503)657-7294 uucp: uunet!nwnexus.WA.COM!vantage!ray -or- uunet!nwnexus!vantage!ray -or- hplabs!hpubvwa!hpupora!vantage!ray Internet: ray%vantage@nwnexus.WA.COM
deepaks@microsoft.UUCP (Deepak SETH) (10/11/90)
Hi, I just started programming on MS C 6.0. I would like to receive copies of the Frequently Asked Questions (FAQ) postings. Could someone tell me how to get back copies of this document and how to get on the mailing list. If someone reading this is responsible for FAQ, could you please put me on the mailing list. Thanks in advance, Deepak Seth internet: deepaks@milton.u.washington.edu uucp: uw-beaver!microsoft!deepaks
scs@adam.mit.edu (Steve Summit) (10/15/90)
This article contains minimal answers to the comp.lang.c frequently asked questions list. Please see the long version (posted on the first of each month) for more detailed explanations and references. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic functions) a constant 0 with an appropriate explicit cast is required. 3. But aren't pointers the same as ints? A: Not since the early days. 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0) which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 8. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 9. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 10. But I once used a compiler that wouldn't work unless NULL was used. A: This compiler was broken. 11. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). 12. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The fact that a preprocessor macro (NULL) is often used suggests that this is done because the value might change later, or on some weird machine. 13. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used in function calls." Arrays and Pointers 14. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. Use extern char a[]. 15. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. Otherwise, the two forms are not interchangeable. 16. So what is meant by the "equivalence of pointers and arrays" in C? A: Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the fact that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. 17. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 18. How do I declare a pointer to an array? A: Usually, you don't want one. Think about using a pointer to one of the array's elements instead. 19. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Order of Evaluation 20. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++); " prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 21. But what about the &&, ||, ?:, and comma operators? A: There is a special exception for those operators; left-to-right evaluation is guaranteed. ANSI C 22. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long and arduous process, this C standard was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. 23. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for full addresses. 24. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. See the full list for details. 25. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed either by using new-style syntax consistently, or by changing the new-style prototype declaration to match the old-style definition. C Preprocessor 26. How can I write a macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 27. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes and no newlines inside quotes. 28. How can I write a cpp macro which takes a variable number of arguments? One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the compiler to indicate a single argument: #define DEBUG(args) {printf("DEBUG: ");printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Variable-Length Argument Lists 29. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. 30. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 31. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 32. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 33. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Memory Allocation 34. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 35. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 36. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. It cannot be used in programs which must be widely portable. Structures 37. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 38. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 39. I have a program which works correctly, but it dumps core after it finishes. Why? A: Check to see if a structure declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. 40. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 41. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 42. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Declarations 43. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 44. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. 45. How do I declare a pointer to a function returning a pointer to a double? A: double *(*p)(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 46. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. Boolean Expressions and Variables 47. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 48. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 49. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enums are compatible with ints. Operating System Dependencies 50. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 51. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 52. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 53. How can a process change an environment variable in its caller? A: In general, it cannot. Stdio 54. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 55. My program's prompts and intermediate output don't always show up on my screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. 56. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 57. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Miscellaneous 58. Can someone tell me how to write itoa? A: Just use sprintf. 59. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 60. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 61. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 62. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups. 63. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 64. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 65. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C and Ritchie's original pdp11 compiler, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 66. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 67. Where can I get a YACC grammar for C? A: See the unabridged list. 68. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. 69. Where can I get extra copies of this list? A: For now, just pull it off the net; it is normally posted on about the first of the month, with an Expiration: line which should keep it around all month. Thanks to Mark Brader, Joe Buehler, Christopher Calabrese, Stephen M. Dunn, Tony Hansen, Guy Harris, Karl Heuer, Blair Houghton, Kirk Johnson, Andrew Koenig, John Lauro, Christopher Lott, Rich Salz, Joshua Simons, and Erik Talvola, who have contributed, directly or indirectly, to this article. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (11/01/90)
[Last modified 10/31/90 by scs.] Certain topics come up again and again on this newsgroup. They are good questions, and the answers may not be immediately obvious, but each time they recur, much net bandwidth and reader time is wasted on repetitive responses, and on tedious corrections to the incorrect answers which are inevitably posted. This article, which is posted monthly, attempts to answer these common questions definitively and succinctly, so that net discussion can move on to more constructive topics without continual regression to first principles. This article does not, and cannot, provide an exhaustive discussion of every subtle point and counterargument which could be mentioned with respect to these topics. Cross-references to standard C publications have been provided, for further study by the interested and dedicated reader. A few of the more perplexing and pervasive topics may be further explored in some in-depth minitreatises posted in conjunction with this article. No mere newsgroup article can substitute for thoughtful perusal of a full-length language reference manual. Anyone interested enough in C to be following this newsgroup should also be interested enough to read and study one or more such manuals, preferably several times. Some vendors' compiler manuals are unfortunately inadequate; a few even perpetuate some of the myths which this article attempts to debunk. Several noteworthy books on C are listed in this article's bibliography. If you have a question about C which is not answered in this article, please try to answer it by checking a few of the referenced books, or by asking knowledgeable colleagues, before posing your question to the net at large. There are many people on the net who are happy to answer questions, but the volume of repetitive answers posted to one question, as well as the growing numbers of questions as the net attracts more readers, can become oppressive. If you have questions or comments prompted by this article, please reply by mail rather than following up -- this article is meant to decrease net traffic, not increase it. This article is always being improved. Your input is welcomed. Send your comments to scs@adam.mit.edu, scs%adam.mit.edu@mit.edu, and/or mit-eddie!adam!scs; this article's From: line may be unusable. The questions answered here are divided into several categories: 1. Null Pointers 2. Arrays and Pointers 3. Order of Evaluation 4. ANSI C 5. C Preprocessor 6. Variable-Length Argument Lists 7. Memory Allocation 8. Structures 9. Declarations 10. Boolean Expressions and Variables 11. Operating System Dependencies 12. Stdio 13. Miscellaneous Herewith, some frequently-asked questions and their answers. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: The language definition states that for each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. That is, the address-of operator & will never yield a null pointer, nor will a successful call to malloc. (malloc returns a null pointer when it fails, and this is a typical use of null pointers: as a "special" pointer value with some other meaning, usually "not allocated" or "not pointing anywhere yet.") A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere (that is, at some random object, or at a garbage or unallocated address). See also question 37. As mentioned in the definition above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different. Although programmers need not know the internal values, the compiler must always be informed which type of null pointer is required, so it can make the distinction if necessary (see below). References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38. 2. How do I "get" a null pointer in my programs? A: According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal: char *p = 0; if(p != 0) However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. For instance, the Unix system call "execl" takes a variable-length, null-pointer- terminated list of character pointer arguments. To generate a null pointer in a function call context, an explicit cast is typically required: execl("/bin/sh", "sh", "-c", "ls", (char *)0); If the (char *) cast were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong.) When function prototypes are in scope, argument passing becomes an "assignment context," and casts may safely be omitted, since the prototype tells the compiler that a pointer is required, and of which type, enabling it to correctly cast unadorned 0's. Function prototypes cannot provide the types for variable arguments in variable-length argument lists, however, so explicit casts are still required for those arguments. It is safest always to cast null pointer function arguments, to guard against varargs functions or those without prototypes, to allow interim use of non-ANSI compilers, and to demonstrate that you know what you are doing. Summary: Unadorned 0 okay: Explicit cast required: initialization function call, no prototype in scope assignments variable argument to comparisons varargs function function call, prototype in scope, fixed argument References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI Sec. 3.2.2.3 . 3. But aren't pointers the same as ints? A: Not since the early days. Attempting to turn pointers into integers, or to build pointers out of integers, has always been machine-dependent and unportable, and doing so is strongly discouraged. (Any object pointer may be cast to the "universal" pointer type void *, or char * under a pre-ANSI compiler, when heterogeneous pointers must be passed around.) References: K&R I Sec. 5.6 pp. 102-3; ANSI Sec. 3.2.2.3 p. 37, Sec. 3.3.4 pp. 46-7. 4. What is NULL and how is it #defined? A: As a stylistic convention, many people prefer not to have unadorned 0's scattered throughout their programs. For this reason, the preprocessor macro NULL is #defined (by <stdio.h> or <stddef.h>), with value 0 (or (void *)0, about which more later). A programmer who wishes to make explicit the distinction between 0 the integer and 0 the null pointer can then use NULL whenever a null pointer is required. This is a stylistic convention only; the preprocessor turns NULL back to 0 which is then recognized by the compiler (in pointer contexts) as before. In particular, a cast may still be necessary before NULL (as before 0) in a function call argument. (The table under question 2 above applies for NULL as well as 0.) NULL should _only_ be used for pointers. It should not be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (ANSI allows the #definition of NULL to be (void *)0, which will not work in non- pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition #define NUL '\0' if you must. References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38, Rationale Sec. 4.1.5 p. 74. 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: Programmers should never need to know the internal representation(s) of null pointers, because they are normally taken care of by the compiler. If a machine uses a nonzero bit pattern for null pointers, it is the compiler's responsibility to generate it when the programmer requests, by writing "0" or "NULL," a null pointer. Therefore, #defining NULL as 0 on a machine for which internal null pointers are nonzero is as valid as on any other, because the compiler must (and can) still generate the machine's correct null pointers in response to unadorned 0's seen in pointer contexts. 6. If NULL were defined as follows: #define NULL (char *)0 wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. The suggested #definition would make uncast NULL arguments to functions expecting pointers to characters to work correctly, but pointer arguments to other types would still be problematical, and legal constructions such as FILE *fp = NULL; could fail. Nevertheless, ANSI C allows the alternate #define NULL (void *)0 definition for NULL. Besides helping incorrect programs to work (but only on machines with all pointers the same, thus questionably valid assistance) this definition may catch programs which use NULL incorrectly (e.g. when the ASCII NUL character was really intended). 7. I use the preprocessor macro #define Nullptr(type) (type *)0 to help me build null pointers of the correct type. A: This trick, though popular with beginning programmers, does not buy much. It is not needed in assignments and comparisons; see question 2. It does not even save keystrokes. Its use suggests to the reader that the author is shaky on the subject of null pointers, and requires the reader to check the #definition of the macro, its invocations, and _all_ other pointer usages much more carefully. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: When C requires the boolean value of an expression (in the if, while, for, and do statements, and with the &&, ||, !, and ?: operators), a false value is produced when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes if(expr) where "expr" is any expression at all, the compiler essentially acts as if it had been written as if(expr != 0) Substituting the trivial pointer expression "p" for "expr," we have if(p) is equivalent to if(p != 0) and this is a comparison context, so the compiler can tell that the (implicit) 0 is a null pointer, and use the correct value. There is no trickery involved here; compilers do work this way, and generate identical code for both statements. The internal representation of a pointer does _not_ matter. The boolean negation operator, !, can be described as follows: !expr is essentially equivalent to expr?0:1 It is left as an exercise for the reader to show that if(!p) is equivalent to if(p == 0) See also question 53. References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and 3.6.5 . 9. If "NULL" and "0" are equivalent, which should I use? A: Many programmers believe that "NULL" should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding "NULL" and "0" is only compounded by hiding "0" behind a #definition, and prefer to use unadorned "0" instead. There is no one right answer. C programmers must understand that "NULL" and "0" are interchangeable and that an uncast "0" is perfectly acceptable in initialization, assignment, and comparison contexts. Any usage of "NULL" (as opposed to "0") should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's. Again, NULL should not be used for other than pointers. Reference: K&R II Sec. 5.4 p. 102. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. Although preprocessor macros are often used in place of numbers because the numbers might change, this is _not_ the reason that NULL is used in place of 0. The language guarantees that source-code 0's (in pointer contexts) generate null pointers. NULL is used only as a stylistic convention. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler was broken. In general, making decisions about a language based on the behavior of one particular compiler is likely to be counterproductive. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. (On some machines the internal value is 0; on others it is not.) A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). When the term "null" or "NULL" is casually used, one of several things may be meant: 1. The conceptual null pointer, the abstract language concept defined in question 1. It is implemented with... 2. The internal (or run-time) representation of a null pointer, which may be different for different pointer types. The actual values should be of concern only to compiler writers. Authors of C programs never see them, since they use... 3. The source code syntax for null pointers, which is the single character "0". It is often hidden behind... 4. The NULL macro, which is #defined to be "0" or "(void *)0". Finally, as a red herring, we have... 5. The ASCII null character (NUL), which does have all bits zero, but has no relation to the null pointer except in name. This article always uses the phrase "null pointer" for sense 1, the character "0" for sense 3, and the capitalized word "NULL" for sense 4. 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: C programmers traditionally like to know more than they need to about the underlying machine implementation. The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. The construct "if(p == 0)" is easily misread as calling for conversion of p to an integral type, rather than 0 to a pointer type, before the comparison. Finally, the distinction between the several uses of the term "null" (listed above) is often overlooked. One good way to wade out of the confusion is to imagine that C had a keyword (perhaps "nil", like Pascal) with which null pointers were requested. The compiler could either turn "nil" into the correct type of null pointer, when it could determine the type from the source code (as it does with 0's in reality), or complain when it could not. Now, in fact, in C the keyword for a null pointer is not "nil" but "0", which works almost as well, except that an uncast "0" in a non-pointer context generates an integer zero instead of an error message, and if that uncast 0 was supposed to be a null pointer, the code may not work. 14. I'm still confused. I just can't understand all this null pointer stuff. A: Follow these two simple rules: 1. When you want to refer to a null pointer in source code, use "0" or "NULL". 2. If the usage of "0" or "NULL" is an argument in a function call, cast it to the pointer type expected by the function being called. The rest of the discussion has to do with other people's misunderstandings, or with the internal representation of null pointers, which you shouldn't need to know. Understand questions 1, 2, and 4, and consider 9 and 13, and you'll do fine. Section 2. Arrays and Pointers 15. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. The type "pointer-to-type-T" is not the same as "array-of-type-T." Use extern char a[]. References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5. 16. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. This identity is related to the fact that arrays "decay" into pointers in expressions. That is, when an array name is mentioned in an expression, it is converted immediately into a pointer to the array's first element. Therefore, an array is never passed to a function; rather a pointer to its first element is passed instead. Allowing pointer parameters to be declared as arrays is a simply a way of making it look as though the array was actually being passed. Some programmers prefer, as a matter of style, to use this syntax to indicate that the pointer parameter is expected to point to the start of an array rather than to some single value. Since functions can never receive arrays as parameters, any parameter declarations which "look like" arrays, e.g. f(a) char a[]; are treated as if they were pointers, since that is what the function will receive if an array is passed: f(a) char *a; To repeat, however, this conversion holds only within function formal parameter declarations, nowhere else. If this conversion confuses you, don't use it; many people have concluded that the confusion it causes outweighs the small advantage of having the declaration "look like" the call and/or the uses within the function. References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3 pp. 33-4. 17. So what is meant by the "equivalence of pointers and arrays" in C? A: Much of the confusion surrounding pointers in C can be traced to this statement. Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. (The fact that, as formal parameters to functions, array-style and pointer-style declarations are in fact interchangeable does nothing to reduce the confusion.) "Equivalence" refers to the fact (mentioned above) that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. That is, if we have char a[10]; char *p = a; int i; we can refer to a[i] and p[i]. (That pointers can be subscripted like arrays is hardly surprising, since arrays have decayed into pointers by the time they are subscripted.) References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec. 5.4.1 p. 93; ANSI Sec. 3.3.2.1, Sec. 3.3.6 . 18. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays are confusing, and it is best to avoid them. (The confusion is heightened by the existence of incorrect compilers, including some versions of pcc and pcc-derived lint's, which improperly accept assignments of multi-dimensional arrays to multi-level pointers.) If you are passing a two-dimensional array to a function: int array[YSIZE][XSIZE]; f(array); the function's declaration should match: f(int a[][XSIZE]) {...} or f(int (*ap)[XSIZE]) {...} /* ap is a pointer to an array */ In the first declaration, the compiler performs the usual implicit rewriting of "array of array" to "pointer to array;" in the second form the pointer declaration is explicit. The called function does not care how big the array is, but it must know its shape, so the "column" dimension XSIZE must be included. In both cases the number of "rows" is irrelevant, and omitted. If a function is already declared as accepting a pointer to a pointer, it is probably incorrect to pass a two-dimensional array directly to it. 19. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. Arrays of type T decay into pointers to type T, which is convenient; subscripting or incrementing the resultant pointer accesses the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally only useful when operating on multidimensional arrays. (See the question above.) If you really need to declare a pointer to an entire array, use something like "int (*ap)[N];" where N is the size of the array. If the size of the array is unknown, N can be omitted, but the resulting type, "pointer to array of unknown size," is almost completely useless. 20. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." The resulting "ragged" array often saves space, although it is not necessarily contiguous in memory as a real array would be. int **array = (int **)malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array[i] = (int *)malloc(ncolumns * sizeof(int)); (In "real" code, of course, each return value from malloc would have to be checked.) You can keep the array's contents contiguous, while making later reallocation of individual rows difficult, with a bit of explicit pointer arithmetic: int **array = (int **)malloc(nrows * sizeof(int *)); array[0] = (int *)malloc(nrows * ncolumns * sizeof(int)); for(i = 1; i < nrows; i++) array[i] = array[0] + i * ncolumns; In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: array[i][j]. If the double indirection implied by the above scheme is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array: int *array = (int *)malloc(nrows * ncolumns * sizeof(int)); However, you must now perform subscript calculations manually, accessing array[i, j] with array[i * ncolumns + j]. (A macro can hide the explicit calculation, but invoking it then requires parentheses and commas which don't look exactly like multidimensional array subscripts.) Section 3. Order of Evaluation 21. Under my compiler, the code int i = 7; printf("%d\n", i++ * i++); prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: Although the postincrement and postdecrement operators ++ and -- perform the operations after yielding the former value, many people misunderstand the implication of "after." It is _not_ guaranteed that the operation is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered "finished" (before the next "sequence point," in ANSI C's terminology). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards. The order of other embedded side effects is similarly undefined. For example, the expression i + (i = 2) may or may not have the value 4. The ANSI C standard declares that code which contains such ambiguous or undefined side effects is not merely undefined, but illegal. Don't even try to find out how your compiler implements such things (contrary to the ill-advised exercises in many C textbooks); as K&R wisely point out, "if you don't know _how_ they are done on various machines, the innocence may help to protect you." References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1. (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.) 22. But what about the &&, ||, and comma operators? I see code like "if((c = getchar()) == EOF || c == '\n')" ... A: There is a special exception for those operators, (as well as ?: ); each of them does imply a sequence point (i.e. left-to-right evaluation is guaranteed). Any book on C should make this clear. References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55, CT&P Sec. 3.7 pp. 46-7. Section 4. ANSI C 23. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long and arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardizes existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the much-lambasted trigraph sequences for transfer of source code between machines with deficient or multinational character sets). The ANSI C standard also formalizes the C run-time library support routines. 24. How can I get a copy of the ANSI C standard? A: Copies are available from American National Standards Institute 1430 Broadway New York, NY 10018 (212) 642-4900 or Global Engineering Documents 2805 McGaw Avenue Irvine, CA 92714 (714) 261-1455 (800) 854-7179 The cost from ANSI is $50.00, plus $6.00 shipping. Quantity discounts are available. (Note that ANSI derives revenues to support its operations from the sale of printed standards, so electronic copies are _not_ available.) 25. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. Check your nearest comp.sources archive. (See also questions 67 and 68.) 26. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". Old C (and ANSI C, in the absence of prototypes) silently promotes floats to doubles when passing them as arguments, and makes a corresponding silent change to formal parameter declarations, so the old-style definition actually says that func takes a double. The problem can be fixed either by using new-style syntax consistently in the definition: int func(float x) { ... } or by changing the new-style prototype declaration to match the old-style definition: extern int func(double); (In this case, it would be clearest to change the old-style definition to use double as well). Reference: ANSI Sec. 3.3.2.2 . Section 5. C Preprocessor 27. How can I write a macro to swap two values? A: There is no good answer to this question. If the values are integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers (and the "obvious" supercompressed implementation for integral types a^=b^=a^=b is, strictly speaking, illegal due to multiple side- effects; and it will not work if the two values are the same variable, and...). If the macro is intended to be used on values of arbitrary type (the usual goal), it cannot use a temporary, since it doesn't know what type of temporary it needs, and standard C does not provide a typeof operator. (GNU C does.) The best all-around solution is probably to forget about using a macro. If you're worried about the use of an ugly temporary, and know that your machine provides an exchange instruction, convince your compiler vendor to recognize the standard three-assignment swap idiom in the optimization phase. 28. I have some old code that tries to construct identifiers with a macro like #define Paste(a, b) a/**/b but it doesn't work any more. A: That comments disappeared entirely and could therefore be used for token pasting was an undocumented feature of some early preprocessor implementations, notably Reiser's. ANSI affirms (as did K&R) that comments are replaced with white space. However, since the need for pasting tokens was demonstrated and real, ANSI introduced a well- defined token-pasting operator, ##, which can be used as follows: #define Paste(a, b) a##b Reference: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7. 29. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (note particularly that an apostrophe within a contracted word in a comment looks like the beginning of a character constant), and no newlines inside quotes. Therefore, natural-language comments should always be written between the "official" comment delimiters /* and */. References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37. 30. What's the best way to write a multi-statement cpp macro? A: The usual goal is to write a macro that can be invoked as if it were a single function-call statement. This means that the "caller" will be supplying the final semicolon, so the macro body should not. The macro body cannot be a simple brace-delineated compound statement, because syntax errors would result if it were invoked (apparently as a single statement, but with a resultant an extra semicolon) as the if branch of an if/else statement with an explicit else clause. The best solution is to use #define Func() do { \ /* declarations */ \ stmt1; \ stmt2; \ /* ... */ \ } while(0) /* (no trailing ; ) */ When the "caller" appends a semicolon, this expansion becomes a single statement regardless of context. (An optimizing compiler will remove any "dead" tests or branches on the constant condition 0, although lint may complain.) If all of the statements in the intended macro are simple expressions, a simpler technique is to separate them with commas and surround them with parentheses. Reference: CT&P Sec. 6.3 pp. 82-3. 31. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the compiler to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); The obvious disadvantage to this trick is that the caller must always remember to use the extra parentheses. (It is often best to use a bona-fide function, which can take a variable number of arguments in a well-defined way, rather than a macro. See questions 32 and 33 below.) Section 6. Variable-Length Argument Lists 32. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. Here is a function which concatenates an arbitrary number of strings into malloc'ed memory, using stdarg: #include <stddef.h> /* for NULL, size_t */ #include <stdarg.h> /* for va_ stuff */ #include <string.h> /* for strcat et al */ #include <stdlib.h> /* for malloc */ /* VARARGS1 */ char *vstrcat(char *first, ...) { size_t len = 0; char *retbuf; va_list argp; char *p; if(first == NULL) return NULL; len = strlen(first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) len += strlen(p); va_end(argp); retbuf = malloc(len + 1); /* +1 for trailing \0 */ if(retbuf == NULL) return NULL; (void)strcpy(retbuf, first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) (void)strcat(retbuf, p); va_end(argp); return retbuf; } Usage is something like char *str = vstrcat("Hello, ", "world!", (char *)NULL); Note the cast on the last argument. (Also note that the caller must free the returned, malloc'ed storage.) Under a pre-ANSI compiler, rewrite the function definition without a prototype ("char *vstrcat(first) char *first; {"), #include <stdio.h> rather than <stddef.h>, replace "#include <stdlib.h>" with "extern char *malloc();", and use int instead of size_t. You may also have to delete the (void) casts, and use the older varargs package instead of stdarg. See the next question for hints. (If you know enough about your machine's architecture, it is possible to pick arguments off of the stack "by hand," but there is little reason to do so, since portable mechanisms exist.) References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 . 33. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. Here is an "error" routine which prints an error message, preceded by the string "error: " and terminated with a newline: #include <stdio.h> #include <stdarg.h> void error(char *fmt, ...) { va_list argp; fprintf(stderr, "error: "); va_start(argp, fmt); vfprintf(stderr, fmt, argp); va_end(argp); fprintf(stderr, "\n"); } To use varargs, instead of stdarg, change the function header to: void error(va_alist) va_dcl { char *fmt; change the va_start line to va_start(argp); and add the line fmt = va_arg(argp, char *); between the calls to va_start and vfprintf. (Note that there is no semicolon after va_dcl.) References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 . 34. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. You're on your own. 35. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Some systems have a nonstandard nargs() function available, but its use is questionable, since it typically returns the number of words pushed, not the number of arguments. (Floating point values and structures are usually passed as several words.) Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. printf-like functions do this by looking for formatting specifiers (%d and the like) in the format string (which is why these functions fail badly if the format string does not match the argument list). Another common technique (useful when the arguments are all of the same type) is to use a sentinel value (often 0, -1, or an appropriately-cast null pointer) at the end of the list (see the vstrcat and execl examples under questions 32 and 2 above). 36. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. You must provide a version of that other function which accepts a va_list pointer, as does vfprintf in the example above. If the arguments must be passed directly as actual arguments (not indirectly through a va_list pointer) to another function which is itself variadic (for which you do not have the option of creating an alternate, va_list-accepting version) no portable solution is possible. (The problem can be solved by resorting to machine-specific assembly language.) Section 7. Memory Allocation 37. Why doesn't this program work? main() { char *answer; printf("Type something:\n"); gets(answer); printf("You typed \"%s\"\n", answer); } A: The pointer variable "answer," which is handed to the gets function as the location into which the response should be stored, has not been set to point to any valid storage. It is an uninitialized variable, just as is the variable i in this example: main() { int i; printf("i = %d\n", i); } That is, we cannot say where the pointer "answer" points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that "answer" starts out as a null pointer.) The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation: #include <stdio.h> main() { char answer[100]; printf("Type something:\n"); fgets(answer, 100, stdin); printf("You typed \"%s\"\n", answer); } Note that this example also uses fgets instead of gets (always a good idea), so that the size of the array can be specified, so that fgets will not overwrite the end of the array if the user types an overly-long line. (Unfortunately, gets and fgets differ in their treatment of the trailing \n.) It would also be possible to use malloc to allocate the answer buffer, and/or to parameterize its size (#define ANSWERSIZE 100). 38. I can't get strcat to work. I tried #include <string.h> main() { char *s1 = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); printf("%s\n", s3); } but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. C does not provide a true string type. C programmers use char *'s for strings, but must always keep allocation in mind. The compiler will only allocate memory for objects explicitly mentioned in the source code (in the case of "strings," this includes character arrays and string literals). The programmer must arrange (explicitly) for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or calling malloc. The simple strcat example could be fixed with something like char s1[20] = "Hello, "; char *s2 = "world!"; Note, however, that strcat appends the string pointed to by its second argument to that pointed to by the first, and merely returns its first argument, so the s3 variable is superfluous. Reference: CT&P Sec. 3.2 p. 32. 39. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages for malloc stated that the contents of freed memory was "left undisturbed;" this ill-advised guarantee is not universal and is not required by ANSI. Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list: struct list *listp, *nextp; for(listp = base; listp != NULL; listp = nextp) { nextp = listp->next; free((char *)listp); } and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer. References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10 p. 95. 40. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context. alloca cannot be written portably, and is difficult to implement on machines without a stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), stdin, 100). For these reasons, alloca cannot be used in programs which must be widely portable, no matter how useful it might be. Section 8. Structures 41. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: What K&R I said was that the restrictions on struct operations would be lifted in a forthcoming version of the compiler, and in fact struct assignment and passing were fully functional in Ritchie's compiler even as K&R I was being published. Although a few early C compilers lacked struct assignment, all modern compilers support it, and it is part of the ANSI C standard, so there should be no reluctance to use it. References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 . 42. How does struct passing and returning work? A: When structures are passed as arguments to functions, the entire struct is typically pushed on the stack, using as many words as are required. (Pointers to functions are often chosen precisely to avoid this overhead.) Structures are typically returned from functions in a location pointed to by an extra, "hidden" argument to the function. Older compilers often used a special, static location for structure returns, although this made struct-valued function nonreentrant, which ANSI disallows. Reference: ANSI Sec. 2.2.3 p. 13. 43. The following program works correctly, but it dumps core after it finishes. Why? struct list { char *item; struct list *next; } /* Here is the main program. */ main(argc, argv) ... A: A missing semicolon causes the compiler to believe that main returns a struct list. (The connection is hard to see because of the intervening comment.) When struct-valued functions are implemented by adding a hidden return pointer, the generated code tries to store a struct with respect to a pointer which was not actually passed (in this case, by the C start-up code). Attempting to store a structure into memory pointed to by the argc or argv value on the stack (where the compiler expected to find the hidden return pointer) causes the core dump. Reference: CT&P Sec. 2.3 pp. 21-2. 44. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. A byte- by-byte comparison could be invalidated by random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison would require unacceptable amounts of repetitive, in-line code for large structures. Either method would not necessarily "do the right thing" with pointer fields: oftentimes, equality should be judged by equality of the things pointed to rather than strict equality of the pointers themselves. If you want to compare two structures, you must write your own function to do so. C++ (among other languages) would let you arrange for the == operator to map to your function. References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Rationale Sec. 3.3.9 p. 47. 45. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. If you don't have it, a suggested implementation is #define offsetof(type, mem) ((size_t) \ ((char *)&((type *) 0)->mem - (char *)((type *) 0))) This implementation is not 100% portable; some compilers may legitimately refuse to accept it. See the next question for a usage hint. Reference: ANSI Sec. 4.1.5 . 46. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is offsetb = offsetof(struct a, b) If structp is a pointer to an instance of this structure, and b is an int field with offset as computed above, b's value can be set indirectly with *(int *)((char *)structp + offsetb) = value; Section 9. Declarations 47. I can't seem to define a linked list node which contains a pointer to itself. I tried typedef struct { char *item; NODEPTR next; } NODE, *NODEPTR; but the compiler gave me error messages. Can't a struct in C contain a pointer to itself? A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. The problem is that the example above attempts to hide the struct pointer behind a typedef, which is not complete at the time it is used. First, rewrite it without a typedef: struct node { char *item; struct node *next; }; Then, if you wish to use typedefs, define them after the fact: typedef struct node NODE, *NODEPTR; Alternatively, define the typedefs first (using the line just above) and follow it with the full definition of struct node, which can then use the NODEPTR typedef for the "next" field. References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 . 48. How can I define a pair of mutually referential structures? I tried typedef struct { int structafield; STRUCTB *bpointer; } STRUCTA; typedef struct { int structbfield; STRUCTA *apointer; } STRUCTB; but the compiler doesn't know about STRUCTB when it is used in struct a. A: Again, the problem is not the pointers but the typedefs. First, define the two structures without using typedefs: struct a { int structafield; struct b *bpointer; }; struct b { int structbfield; struct a *apointer; }; The compiler can accept the field declaration struct b *bpointer within struct a, even though it has not yet heard of struct b. Occasionally it is necessary to precede this couplet with the empty declaration struct b; to mask the declarations (if in an inner scope) from a different struct b in an outer scope. Again, the typedefs could also be defined before, and then used within, the definitions for struct a and struct b. Problems arise only when an attempt is made to define and use a typedef within the same declaration. References: H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 . 49. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: This question can be answered in at least three ways (all assume the hypothetical array is to have 5 elements): 1. char *(*(*a[5])())(); 2. Build it up in stages, using typedefs: typedef char *cp; /* pointer to char */ typedef cp fpc(); /* function returning pointer to char */ typedef fpc *pfpc; /* pointer to above */ typedef pfpc fpfpc(); /* function returning... */ typedef fpfpc *pfpfpc; /* pointer to... */ pfpfpc a[5]; /* array of... */ 3. Use the cdecl program, which turns English into C and vice versa: $ cdecl cdecl> declare a as array 5 of pointer to function returning pointer to function returning pointer to char char *(*(*a[5])())() cdecl> cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions). Any good book on C should explain tricks for reading these complicated C declarations "inside out" to understand them ("declaration mimics use"). Reference: H&S Sec. 5.10.1 p. 116. 50. So where can I get cdecl? A: Several public-domain versions are available. One is in volume 14 of comp.sources.unix . (Commercial versions may also be available, at least one of which was shamelessly lifted from the public domain copy submitted by Graham Ross, one of cdecl's originators.) See question 68. Reference: K&R II Sec. 5.12 . 51. I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one? A: Use something like extern int func(); int (*fp)() = func; When the name of a function appears in an expression but is not being called (i.e. is not followed by a "("), its address is implicitly taken, just as is done for arrays. An explicit extern declaration for the function is normally needed, since implicit external function declaration does not happen in this case (again, because the function name is not followed by a "("). Section 10. Boolean Expressions and Variables 52. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. (Using an int for a boolean may be faster, while using char will probably save data space.) The choice between #defines and enums is arbitrary and not terribly interesting. Use any of #define TRUE 1 #define YES 1 #define FALSE 0 #define NO 0 enum bool {false, true}; enum bool {no, yes}; or use raw 1 and 0, as long as you are consistent within one program or project. (The enum may be preferable if your debugger expands enum values when examining variables.) Some people prefer variants like #define TRUE (1==1) #define FALSE (!TRUE) or define "helper" macros such as #define Istrue(e) ((e) != 0) These don't buy anything (see below). 53. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test if((a == b) == TRUE) will succeed (if a, in fact, equals b and TRUE is 1), but this code is obviously silly. In general, explicit tests against TRUE and FALSE are undesirable, because some library functions (notably isupper, isalpha, etc.) return, on success, a nonzero value which is _not_ necessarily 1. (Besides, if you believe that "if((a == b) == TRUE)" is an improvement over "if(a == b)", why stop there? Why not use "if(((a == b) == TRUE) == TRUE)"?) A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable or as the return value from a Boolean function, never in a comparison. Preprocessor macros like TRUE and FALSE (and, in fact, NULL) are used for code readability, not because the underlying values might ever change. That "true" is 1 and "false" (and source-code null pointers) 0 is guaranteed by the language. (See also question 8.) References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5 . 54. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. Although many people might have wished otherwise, the ANSI standard says that enums may be freely intermixed with integral types, without errors. (If such intermixing were disallowed without explicit casts, judicious use of enums could catch certain programming errors.) The advantages of enums are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enum variables are examined, and that a compiler may generate nonfatal warnings when enums and ints are indiscriminately mixed (such mixing can still be considered bad style even though it is not strictly illegal). References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 . Section 11. Operating System Dependencies 55. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. The delivery of characters from a "keyboard" to a C program is a function of the operating system in use, and cannot be standardized by the C language. If you are using curses, use its cbreak() function. Under UNIX, use ioctl to play with the terminal driver modes (CBREAK or RAW under "classic" versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or Posix systems). Under MS-DOS, use getch(). Under other operating systems, you're on your own. Beware that some operating systems make this sort of thing impossible, because character collection into input lines is done by peripheral processors not under direct control of the CPU running your program. Operating system specific questions are not appropriate for comp.lang.c . Many common questions are answered in frequently- asked questions postings in such groups as comp.unix.questions and comp.os.msdos.programmer . Note that the answers are often not unique even across different versions of Unix. Bear in mind when answering system-specific questions that the answer that applies to your system may not apply to everyone else's. References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1. 56. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. Some versions of curses have a nodelay() function. Depending on your system, you may also be able to use "nonblocking I/O", or a system call named "select", or the FIONREAD ioctl, or O_NDELAY, or a kbhit() routine. 57. How can my program discover the complete pathname to the executable file from which it was invoked? A: Depending on the operating system, argv[0] may contain all or part of the pathname. (It may also contain nothing.) You may be able to duplicate the command language interpreter's search path logic to locate the executable if the name in argv[0] is incomplete. However, there is no guaranteed or portable solution. 58. How can a process change an environment variable in its caller? A: In general, it cannot. Different operating systems implement name/value functionality similar to the Unix environment in many different ways. Whether the "environment" can be usefully altered by a running program, and if so, how, is entirely system-dependent. Under Unix, a process can modify its own environment (Some systems provide setenv() or putenv() functions to do this), and the modified environment is passed on to any child processes, but it is not propagated back to the parent process. (The environment of the parent process can only be altered if the parent is explicitly set up to listen for some kind of change requests. The conventional execution of the BSD "tset" program in .profile and .login files effects such a scheme.) 59. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and some MS-DOS compilers supply chsize(), but there is no portable solution. Section 12. Stdio 60. Why does errno contain ENOTTY after a call to printf? A: Many implementations of the stdio package adjust their behavior slightly if stdout is a terminal. To make the determination, these implementations perform an operation which fails (with ENOTTY) if stdout is not a terminal. Although the output operation goes on to complete successfully, errno still contains ENOTTY. This behavior can be mildly confusing, but it is not strictly incorrect, because it is only meaningful for a program to inspect the contents of errno after an error has occurred (that is, after a library function that sets errno on error has returned an error code). Reference: CT&P Sec. 5.4 p. 73. 61. My program's prompts and intermediate output don't always show up on my screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. Several mechanisms attempt to perform the fflush for you, at the "right time," but they do not always work, particularly when stdout is a pipe rather than a terminal. 62. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. In particular, "\n" in a format string does not mean "expect a newline", it means "discard all whitespace". But the only way to discard all whitespace is to continue reading the stream until a non-whitespace character is seen (which is then left in the buffer for the next input), so the effect is that it keeps going until it sees a nonblank line. 63. So what should I use instead? A: You could use a "%c" format, which will read one character that you can then manually compare against a newline; or "%*c" and no variable if you're willing to trust the user to hit a newline; or "%*[^\n]%*c" to discard everything up to and including the newline. Usually the best solution is to use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Section 13. Miscellaneous 64. Can someone tell me how to write itoa (the inverse of atoi)? A: Just use sprintf. (You'll have to allocate space for the result somewhere anyway; see questions 37 and 38.) 65. I know that the library routine localtime will convert a time_t into a broken-down struct tm, and that ctime will convert a time_t to a printable string. How can I perform the inverse operations of converting a struct tm or a string into a time_t? A: ANSI C specifies a library routine, mktime, which converts a struct tm to a time_t. Several public-domain versions of this routine are available in case your compiler does not support it yet. Converting a string to a time_t is harder, because of the wide variety of date and time formats which should be parsed. Public- domain routines have been written for performing this function, as well, but they are less likely to become standardized. References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI Sec. 4.12.2.3 . 66. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: Standard headers exist in part so that definitions appropriate to your compiler, operating system, and processor can be supplied. You cannot just pick up a copy of someone else's header file and expect it to work, unless that person uses exactly the same environment. Ask your compiler vendor why the file was not provided (or to send another copy, if you've merely lost it). 67. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available: p2c written by Dave Gillespie, and posted to comp.sources.unix in March, 1990 (Volume 21). ptoc another comp.sources.unix contribution, this one written in Pascal (comp.sources.unix, Volume 10, also patches in Volume 13?). f2c jointly developed by people from Bell Labs, Bellcore, and Carnegie Mellon. To find about f2c, send the message "send index from f2c" to netlib@research.att.com or research!netlib. FOR_C Available from: Cobalt Blue 2940 Union Ave., Suite C San Jose, CA 95124 (408) 723-0474 Promula.Fortran Available from Promula Development Corp. 3620 N. High St., Suite 301 Columbus, OH 43214 (614) 263-5454 The comp.sources.unix archives also contain converters between "K&R" C and ANSI C. 68. Where can I get copies of all these public-domain programs? A: If you have access to Usenet, see the regular postings in the comp.sources.unix and comp.sources.misc newsgroups, which describe, in some detail, the archiving policies and how to retrieve copies. The usual approach is to use anonymous ftp and/or uucp from a central, public-spirited site, such as uunet.uu.net. However, this article cannot track or list all of the available sites and how to access them. 69. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? (And vice versa?) A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use, and may not be possible at all. Read your compiler documentation very carefully; sometimes there is a "mixed-language programming guide," although the techniques for passing arguments correctly are often arcane. 70. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good, mostly because of the possibility of accidentally leaving comments unclosed by including the characters "/*" within them. For this reason, it is usually better to "comment out" large sections of code, which might contain comments, with #ifdef or #if 0. The character sequences /* and */ are not special within double- quoted strings, and do not therefore introduce comments, because a program (particularly one which is generating C code as output) might want to print them. It is hard to imagine why anyone would want or need to place a comment inside a quoted string. It is easy to imagine a program needing to print "/*". Reference: ANSI Rationale Sec. 3.1.9 p. 33. 71. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C and Ritchie's original PDP-11 compiler, attempt to leave out floating point support if it looks like it will not be needed. In particular, the non-floating-point versions of printf and scanf save space by not including code to handle %e, %f, and %g. Occasionally the heuristics for "is the program using floating point?" are insufficient, and the programmer must insert one dummy explicit floating-point operation to force loading of floating-point support. Unfortunately, an apparently common sort of program (thus the frequency of the question) uses scanf to read, and/or printf to print, floating-point values upon which no arithmetic is done, which elicits the problem under Turbo C. In general, questions about a particular compiler are inappropriate for comp.lang.c . Problems with PC compilers, for instance, will find a more receptive audience in a PC newsgroup. 72. Does anyone have a C compiler test suite I can use? A: Plum Hall, (1 Spruce Ave., Cardiff, NJ 08232, USA), among others, sells one. 73. Where can I get a YACC grammar for C? A: The definitive grammar is of course the one in the ANSI standard. Several copies are floating around; keep your eyes open. There is one on uunet.uu.net (192.48.96.2) in net.sources/ansi.c.grammar.Z . FSF's GNU C compiler contains a grammar, as does the appendix to K&R II. Reference: ANSI Sec. A.2 . 74. Where can I get the "Indian Hill Style Guide" and other coding standards? A: Various standards are available for anonymous ftp from: Site: File or directory: cs.washington.edu ~ftp/pub/cstyle.tar.Z (128.95.1.4) (the updated Indian Hill guide) cs.toronto.edu doc/programming giza.cis.ohio-state.edu pub/style-guide prep.ai.mit.edu pub/gnu/standards.text 75. Where can I get extra copies of this list? What about back issues? A: For now, just pull it off the net; it is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Eventually, it may be available for anonymous ftp, or via a mailserver. (Note that the size of the list is monotonically increasing; older copies are obsolete and don't contain anything, except the occasional typo, that the current list doesn't.) Bibliography ANSI American National Standard for Information Systems -- Programming Language -- C, ANSI X3.159-1989. H&S Samuel P. Harbison and Guy L. Steele, C: A Reference Manual, Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0. PCS Mark R. Horton, Portable C Software, Prentice Hall, 1990, ISBN 0-13-868050-7. K&R I Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall, 1978, ISBN 0-13-110163-3. K&R II Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Second Edition, Prentice Hall, 1988, ISBN 0-13- 110362-8, 0-13-110370-9. CT&P Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989, ISBN 0-201-17928-8. There is a more extensive bibliography in the revised Indian Hill style guide; see question 74. Acknowledgements Thanks to Mark Brader, Joe Buehler, rayc, Christopher Calabrese, Ray Dunn, Stephen M. Dunn, Bjorn Engsig, Doug Gwyn, Tony Hansen, Joe Harrington, Guy Harris, Karl Heuer, Blair Houghton, Kirk Johnson, Andrew Koenig, John Lauro, Christopher Lott, Evan Manning, Mark Moraes Francois Pinard, randall@virginia, Rich Salz, Joshua Simons, Henry Spencer, Erik Talvola, Chris Torek, and Freek Wiedijk, who have contributed, directly or indirectly, to this article. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained. The C code in this article (vstrcat, error, etc.) is public domain and may be used without restriction.
scs@adam.mit.edu (Steve Summit) (11/01/90)
This article contains minimal answers to the comp.lang.c frequently asked questions list. Please see the long version for more detailed explanations and references. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic functions) a constant 0 with an appropriate explicit cast is required. 3. But aren't pointers the same as ints? A: Not since the early days. 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0), which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. I use the preprocessor macro "#define Nullptr(type) (type *)0 " to help me build null pointers of the correct type. A: This trick does not buy much. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 9. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler was broken. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. 14. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." Section 2. Arrays and Pointers 15. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. Use extern char a[]. 16. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. Otherwise, the two forms are not interchangeable. 17. So what is meant by the "equivalence of pointers and arrays" in C? A: Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the fact that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. 18. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 19. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. 20. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Section 3. Order of Evaluation 21. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++); " prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 22. But what about the &&, ||, and comma operators? A: There is a special exception for those operators, (as well as ?: ); left-to-right evaluation is guaranteed. Section 4. ANSI C 23. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long and arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. 24. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for full addresses. 25. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. 26. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed by using either new-style (prototype) or old-style syntax consistently. Section 5. C Preprocessor 27. How can I write a macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 28. I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b ", but it doesn't work any more. A: Use the ANSI token-pasting operator ##. 29. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes and no newlines inside quotes. 30. What's the best way to write a multi-statement cpp macro? A: #define Func() do {stmt1; stmt2; ... } while(0) /*(no trailing ;) */ 31. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the compiler to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Section 6. Variable-Length Argument Lists 32. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. 33. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 34. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 35. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 36. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Section 7. Memory Allocation 37. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 38. I can't get strcat to work. I tried "char *s1 = "Hello, ", *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. 39. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 40. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. Section 8. Structures 41. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 42. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 43. I have a program which works correctly, but it dumps core after it finishes. Why? A: Check to see if a structure declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. 44. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 45. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 46. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Section 9. Declarations 47. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 48. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. 49. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: char *(*(*a[5])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 50. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. 51. How do I initialize a pointer to a function? A: Use something like "extern int func(); int (*fp)() = func; " Section 10. Boolean Expressions and Variables 52. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 53. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 54. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enums are compatible with integers. Section 11. Operating System Dependencies 55. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 56. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 57. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 58. How can a process change an environment variable in its caller? A: In general, it cannot. 59. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and some MS-DOS compilers supply chsize(), but there is no portable solution. Section 12. Stdio 60. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 61. My program's prompts and intermediate output don't always show up on my screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. 62. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 63. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Section 13. Miscellaneous 64. Can someone tell me how to write itoa? A: Just use sprintf. 65. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 66. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 67. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 68. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups. 69. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 70. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 71. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C and Ritchie's original PDP-11 compiler, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 72. Does anyone have a C compiler test suite I can use? A: Plum Hall among others, sells one. 73. Where can I get a YACC grammar for C? A: See the unabridged list. 74. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. 75. Where can I get extra copies of this list? A: For now, just pull it off the net; it is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (11/15/90)
This article contains minimal answers to the comp.lang.c frequently asked questions list. Please see the long version (posted on the first of each month) for more detailed explanations and references. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic functions) a constant 0 with an appropriate explicit cast is required. 3. But aren't pointers the same as ints? A: Not since the early days. 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0), which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. I use the preprocessor macro "#define Nullptr(type) (type *)0 " to help me build null pointers of the correct type. A: This trick does not buy much. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 9. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler was broken. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. 14. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." Section 2. Arrays and Pointers 15. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. Use extern char a[]. 16. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. Otherwise, the two forms are not interchangeable. 17. So what is meant by the "equivalence of pointers and arrays" in C? A: Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the fact that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. 18. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 19. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. 20. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Section 3. Order of Evaluation 21. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++); " prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 22. But what about the &&, ||, and comma operators? A: There is a special exception for those operators, (as well as ?: ); left-to-right evaluation is guaranteed. Section 4. ANSI C 23. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long and arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. 24. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for full addresses. 25. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. 26. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed by using either new-style (prototype) or old-style syntax consistently. Section 5. C Preprocessor 27. How can I write a macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 28. I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b ", but it doesn't work any more. A: Use the ANSI token-pasting operator ##. 29. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes and no newlines inside quotes. 30. What's the best way to write a multi-statement cpp macro? A: #define Func() do {stmt1; stmt2; ... } while(0) /*(no trailing ;) */ 31. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the compiler to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Section 6. Variable-Length Argument Lists 32. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. 33. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 34. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 35. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 36. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Section 7. Memory Allocation 37. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 38. I can't get strcat to work. I tried "char *s1 = "Hello, ", *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. 39. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 40. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. Section 8. Structures 41. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 42. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 43. I have a program which works correctly, but it dumps core after it finishes. Why? A: Check to see if a structure declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. 44. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 45. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 46. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Section 9. Declarations 47. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 48. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. 49. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: char *(*(*a[5])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 50. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. 51. How do I initialize a pointer to a function? A: Use something like "extern int func(); int (*fp)() = func; " Section 10. Boolean Expressions and Variables 52. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 53. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 54. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enums are compatible with integers. Section 11. Operating System Dependencies 55. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 56. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 57. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 58. How can a process change an environment variable in its caller? A: In general, it cannot. 59. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and some MS-DOS compilers supply chsize(), but there is no portable solution. Section 12. Stdio 60. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 61. My program's prompts and intermediate output don't always show up on my screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. 62. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 63. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Section 13. Miscellaneous 64. Can someone tell me how to write itoa? A: Just use sprintf. 65. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 66. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 67. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 68. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups. 69. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 70. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 71. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C and Ritchie's original PDP-11 compiler, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 72. Does anyone have a C compiler test suite I can use? A: Plum Hall among others, sells one. 73. Where can I get a YACC grammar for C? A: See the unabridged list. 74. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. 75. Where can I get extra copies of this list? A: For now, just pull it off the net; it is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (12/01/90)
[Last modified 11/30/90 by scs.] This article contains minimal answers to the comp.lang.c frequently asked questions list. Please see the long version for more detailed explanations and references. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic functions) a constant 0 with an appropriate explicit cast is required. 3. But aren't pointers the same as ints? A: Not since the early days. 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0), which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. I use the preprocessor macro "#define Nullptr(type) (type *)0 " to help me build null pointers of the correct type. A: This trick does not buy much. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 9. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler was broken. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. 14. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." Section 2. Arrays and Pointers 15. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. Use extern char a[]. 16. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. Otherwise, the two forms are not interchangeable. 17. So what is meant by the "equivalence of pointers and arrays" in C? A: Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the fact that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. 18. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 19. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. 20. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Section 3. Order of Evaluation 21. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++); " prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 22. But what about the &&, ||, and comma operators? A: There is a special exception for those operators, (as well as ?: ); left-to-right evaluation is guaranteed. Section 4. ANSI C 23. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. 24. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for addresses. 25. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. 26. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed by using either new-style (prototype) or old-style syntax consistently. 27. Why does the ANSI Standard not guarantee more than six monocase characters for external identifier significance? A: The main problem is older linkers. Section 5. C Preprocessor 28. How can I write a macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 29. I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b ", but it doesn't work any more. A: Use the ANSI token-pasting operator ##. 30. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (i.e. no single apostrophes), and no newlines inside quotes. 31. What's the best way to write a multi-statement cpp macro? A: #define Func() do {stmt1; stmt2; ... } while(0) /* (no trailing ;) */ 32. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the compiler to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Section 6. Variable-Length Argument Lists 33. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. 34. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 35. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 36. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 37. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Section 7. Memory Allocation 38. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 39. I can't get strcat to work. I tried "char *s1 = "Hello, ", *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. Q: But the man page for strcat said that it took two char *'s as arguments. How was I supposed to know to allocate things? A: In general, when using pointers you _always_ have to worry about memory allocation, at least to make sure that the compiler is doing it for you. 40. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 41. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. Section 8. Structures 42. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 43. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 44. I have a program which works correctly, but dumps core after it finishes. Why? A: Check to see if a structure declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. 45. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 46. I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make the array act like it had several elements. Is this legal and/or portable? A: It is surprisingly difficult to determine whether the ANSI C standard allows or disallows it. 47. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 48. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Section 9. Declarations 49. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 50. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. 51. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: char *(*(*a[5])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 52. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. 53. How do I initialize a pointer to a function? A: Use something like "extern int func(); int (*fp)() = func; " . 54. I've seen different methods used for calling through functions to pointers. A: The extra parentheses and explicit * are now officially optional, although "Classic C" required them. Section 10. Boolean Expressions and Variables 55. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 56. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 57. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enums are compatible with integers. Section 11. Operating System Dependencies 58. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 59. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 60. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 61. How can a process change an environment variable in its caller? A: In general, it cannot. 62. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and some MS-DOS compilers supply chsize(), but there is no portable solution. Section 12. Stdio 63. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 64. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. 65. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 66. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Section 13. Miscellaneous 67. Can someone tell me how to write itoa? A: Just use sprintf. 68. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 69. How can I write data files which can be read on other machines with different word size, byte order, or floating point formats? A: The best solution is to use a text file. 70. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 71. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 72. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups for information. 73. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 74. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 75. My floating-point calculations are acting strangely and giving me different answers on different machines. A: See the full list for a brief explanation, or any good programming book for a better one. 76. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 77. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 78. Where can I get a YACC grammar for C? A: See the unabridged list. 79. What's the best style for code layout in C? A: There is no one "best style," but see the full list for a few suggestions. 80. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. 81. How do you pronounce "char"? What's that funny name for the "#" character? A: Rhyme it with "far" or "bear" (your choice); "octothorpe." 82. Where can I get extra copies of this list? A: For now, just pull it off the net; it is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (01/01/91)
[Last modified December 16, 1990 by scs.] Certain topics come up again and again on this newsgroup. They are good questions, and the answers may not be immediately obvious, but each time they recur, much net bandwidth and reader time is wasted on repetitive responses, and on tedious corrections to the incorrect answers which are inevitably posted. This article, which is posted monthly, attempts to answer these common questions definitively and succinctly, so that net discussion can move on to more constructive topics without continual regression to first principles. This article does not, and cannot, provide an exhaustive discussion of every subtle point and counterargument which could be mentioned with respect to these topics. Cross-references to standard C publications have been provided, for further study by the interested and dedicated reader. A few of the more perplexing and pervasive topics may be further explored in some in-depth minitreatises posted in conjunction with this article. No mere newsgroup article can substitute for thoughtful perusal of a full-length language reference manual. Anyone interested enough in C to be following this newsgroup should also be interested enough to read and study one or more such manuals, preferably several times. Some vendors' compiler manuals are unfortunately inadequate; a few even perpetuate some of the myths which this article attempts to debunk. Several noteworthy books on C are listed in this article's bibliography. If you have a question about C which is not answered in this article, please try to answer it by checking a few of the referenced books, or by asking knowledgeable colleagues, before posing your question to the net at large. There are many people on the net who are happy to answer questions, but the volume of repetitive answers posted to one question, as well as the growing numbers of questions as the net attracts more readers, can become oppressive. If you have questions or comments prompted by this article, please reply by mail rather than following up -- this article is meant to decrease net traffic, not increase it. This article is always being improved. Your input is welcomed. Send your comments to scs@adam.mit.edu, scs%adam.mit.edu@mit.edu, and/or mit-eddie!adam!scs; this article's From: line may be unusable. The questions answered here are divided into several categories: 1. Null Pointers 2. Arrays and Pointers 3. Order of Evaluation 4. ANSI C 5. C Preprocessor 6. Variable-Length Argument Lists 7. Memory Allocation 8. Structures 9. Declarations 10. Boolean Expressions and Variables 11. Operating System Dependencies 12. Stdio 13. Miscellaneous Herewith, some frequently-asked questions and their answers: Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: The language definition states that for each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. That is, the address-of operator & will never yield a null pointer, nor will a successful call to malloc. (malloc returns a null pointer when it fails, and this is a typical use of null pointers: as a "special" pointer value with some other meaning, usually "not allocated" or "not pointing anywhere yet.") A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere (that is, at some random object, or at a garbage or unallocated address). See also question 38. As mentioned in the definition above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different. Although programmers need not know the internal values, the compiler must always be informed which type of null pointer is required, so it can make the distinction if necessary (see below). References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38. 2. How do I "get" a null pointer in my programs? A: According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal: char *p = 0; if(p != 0) However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. For instance, the Unix system call "execl" takes a variable-length, null-pointer- terminated list of character pointer arguments. To generate a null pointer in a function call context, an explicit cast is typically required: execl("/bin/sh", "sh", "-c", "ls", (char *)0); If the (char *) cast were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong.) When function prototypes are in scope, argument passing becomes an "assignment context," and casts may safely be omitted, since the prototype tells the compiler that a pointer is required, and of which type, enabling it to correctly cast unadorned 0's. Function prototypes cannot provide the types for variable arguments in variable-length argument lists, however, so explicit casts are still required for those arguments. It is safest always to cast null pointer function arguments, to guard against varargs functions or those without prototypes, to allow interim use of non-ANSI compilers, and to demonstrate that you know what you are doing. Summary: Unadorned 0 okay: Explicit cast required: initialization function call, no prototype in scope assignments variable argument to comparisons varargs function function call, prototype in scope, fixed argument References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI Sec. 3.2.2.3 . 3. But aren't pointers the same as ints? A: Not since the early days. Attempting to turn pointers into integers, or to build pointers out of integers, has always been machine-dependent and unportable, and doing so is strongly discouraged. (Any object pointer may be cast to the "universal" pointer type void *, or char * under a pre-ANSI compiler, when heterogeneous pointers must be passed around.) References: K&R I Sec. 5.6 pp. 102-3; ANSI Sec. 3.2.2.3 p. 37, Sec. 3.3.4 pp. 46-7. 4. What is NULL and how is it #defined? A: As a stylistic convention, many people prefer not to have unadorned 0's scattered throughout their programs. For this reason, the preprocessor macro NULL is #defined (by <stdio.h> or <stddef.h>), with value 0 (or (void *)0, about which more later). A programmer who wishes to make explicit the distinction between 0 the integer and 0 the null pointer can then use NULL whenever a null pointer is required. This is a stylistic convention only; the preprocessor turns NULL back to 0 which is then recognized by the compiler (in pointer contexts) as before. In particular, a cast may still be necessary before NULL (as before 0) in a function call argument. (The table under question 2 above applies for NULL as well as 0.) NULL should _only_ be used for pointers. It should not be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (ANSI allows the #definition of NULL to be (void *)0, which will not work in non- pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition #define NUL '\0' if you must. References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38, Rationale Sec. 4.1.5 p. 74. 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: Programmers should never need to know the internal representation(s) of null pointers, because they are normally taken care of by the compiler. If a machine uses a nonzero bit pattern for null pointers, it is the compiler's responsibility to generate it when the programmer requests, by writing "0" or "NULL," a null pointer. Therefore, #defining NULL as 0 on a machine for which internal null pointers are nonzero is as valid as on any other, because the compiler must (and can) still generate the machine's correct null pointers in response to unadorned 0's seen in pointer contexts. 6. If NULL were defined as follows: #define NULL (char *)0 wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. The suggested #definition would make uncast NULL arguments to functions expecting pointers to characters to work correctly, but pointer arguments to other types would still be problematical, and legal constructions such as FILE *fp = NULL; could fail. Nevertheless, ANSI C allows the alternate #define NULL (void *)0 definition for NULL. Besides helping incorrect programs to work (but only on machines with all pointers the same, thus questionably valid assistance) this definition may catch programs which use NULL incorrectly (e.g. when the ASCII NUL character was really intended). 7. I use the preprocessor macro #define Nullptr(type) (type *)0 to help me build null pointers of the correct type. A: This trick, though popular with beginning programmers, does not buy much. It is not needed in assignments and comparisons; see question 2. It does not even save keystrokes. Its use suggests to the reader that the author is shaky on the subject of null pointers, and requires the reader to check the #definition of the macro, its invocations, and _all_ other pointer usages much more carefully. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: When C requires the boolean value of an expression (in the if, while, for, and do statements, and with the &&, ||, !, and ?: operators), a false value is produced when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes if(expr) where "expr" is any expression at all, the compiler essentially acts as if it had been written as if(expr != 0) Substituting the trivial pointer expression "p" for "expr," we have if(p) is equivalent to if(p != 0) and this is a comparison context, so the compiler can tell that the (implicit) 0 is a null pointer, and use the correct value. There is no trickery involved here; compilers do work this way, and generate identical code for both statements. The internal representation of a pointer does _not_ matter. The boolean negation operator, !, can be described as follows: !expr is essentially equivalent to expr?0:1 It is left as an exercise for the reader to show that if(!p) is equivalent to if(p == 0) See also question 57. References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and 3.6.5 . 9. If "NULL" and "0" are equivalent, which should I use? A: Many programmers believe that "NULL" should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding "NULL" and "0" is only compounded by hiding "0" behind a #definition, and prefer to use unadorned "0" instead. There is no one right answer. C programmers must understand that "NULL" and "0" are interchangeable and that an uncast "0" is perfectly acceptable in initialization, assignment, and comparison contexts. Any usage of "NULL" (as opposed to "0") should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's. Again, NULL should not be used for other than pointers. Reference: K&R II Sec. 5.4 p. 102. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. Although preprocessor macros are often used in place of numbers because the numbers might change, this is _not_ the reason that NULL is used in place of 0. The language guarantees that source-code 0's (in pointer contexts) generate null pointers. NULL is used only as a stylistic convention. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler was broken. In general, making decisions about a language based on the behavior of one particular compiler is likely to be counterproductive. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. (On some machines the internal value is all-bits-0; on others it is not.) A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). When the term "null" or "NULL" is casually used, one of several things may be meant: 1. The conceptual null pointer, the abstract language concept defined in question 1. It is implemented with... 2. The internal (or run-time) representation of a null pointer, which may or may not be all-bits-0 and which may be different for different pointer types. The actual values should be of concern only to compiler writers. Authors of C programs never see them, since they use... 3. The source code syntax for null pointers, which is the single character "0". It is often hidden behind... 4. The NULL macro, which is #defined to be "0" or "(void *)0". Finally, as a red herring, we have... 5. The ASCII null character (NUL), which does have all bits zero, but has no relation to the null pointer except in name. This article always uses the phrase "null pointer" for sense 1, the character "0" for sense 3, and the capitalized word "NULL" for sense 4. 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: C programmers traditionally like to know more than they need to about the underlying machine implementation. The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. The construct "if(p == 0)" is easily misread as calling for conversion of p to an integral type, rather than 0 to a pointer type, before the comparison. Finally, the distinction between the several uses of the term "null" (listed above) is often overlooked. One good way to wade out of the confusion is to imagine that C had a keyword (perhaps "nil", like Pascal) with which null pointers were requested. The compiler could either turn "nil" into the correct type of null pointer, when it could determine the type from the source code (as it does with 0's in reality), or complain when it could not. Now, in fact, in C the keyword for a null pointer is not "nil" but "0", which works almost as well, except that an uncast "0" in a non-pointer context generates an integer zero instead of an error message, and if that uncast 0 was supposed to be a null pointer, the code may not work. 14. I'm still confused. I just can't understand all this null pointer stuff. A: Follow these two simple rules: 1. When you want to refer to a null pointer in source code, use "0" or "NULL". 2. If the usage of "0" or "NULL" is an argument in a function call, cast it to the pointer type expected by the function being called. The rest of the discussion has to do with other people's misunderstandings, or with the internal representation of null pointers, which you shouldn't need to know. Understand questions 1, 2, and 4, and consider 9 and 13, and you'll do fine. Section 2. Arrays and Pointers 15. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. The type "pointer-to-type-T" is not the same as "array-of-type-T." Use extern char a[]. References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5. 16. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. This identity is related to the fact that arrays "decay" into pointers in expressions. That is, when an array name is mentioned in an expression, it is converted immediately into a pointer to the array's first element. Therefore, an array is never passed to a function; rather a pointer to its first element is passed instead. Allowing pointer parameters to be declared as arrays is a simply a way of making it look as though the array was actually being passed. Some programmers prefer, as a matter of style, to use this syntax to indicate that the pointer parameter is expected to point to the start of an array rather than to some single value. Since functions can never receive arrays as parameters, any parameter declarations which "look like" arrays, e.g. f(a) char a[]; are treated as if they were pointers, since that is what the function will receive if an array is passed: f(a) char *a; To repeat, however, this conversion holds only within function formal parameter declarations, nowhere else. If this conversion bothers you, don't use it; many people have concluded that the confusion it causes outweighs the small advantage of having the declaration "look like" the call and/or the uses within the function. References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3 pp. 33-4. 17. So what is meant by the "equivalence of pointers and arrays" in C? A: Much of the confusion surrounding pointers in C can be traced to a misunderstanding of this statement. Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. (The fact that, as formal parameters to functions, array-style and pointer-style declarations are in fact interchangeable does nothing to reduce the confusion.) "Equivalence" refers to the fact (mentioned above) that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. That is, if we have char a[10]; char *p = a; int i; we can refer to a[i] and p[i]. (That pointers can be subscripted like arrays is hardly surprising, since arrays have decayed into pointers by the time they are subscripted.) References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec. 5.4.1 p. 93; ANSI Sec. 3.3.2.1, Sec. 3.3.6 . 18. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays are confusing, and it is best to avoid them. (The confusion is heightened by the existence of incorrect compilers, including some versions of pcc and pcc-derived lint's, which improperly accept assignments of multi-dimensional arrays to multi-level pointers.) If you are passing a two-dimensional array to a function: int array[YSIZE][XSIZE]; f(array); the function's declaration should match: f(int a[][XSIZE]) {...} or f(int (*ap)[XSIZE]) {...} /* ap is a pointer to an array */ In the first declaration, the compiler performs the usual implicit rewriting of "array of array" to "pointer to array;" in the second form the pointer declaration is explicit. The called function does not care how big the array is, but it must know its shape, so the "column" dimension XSIZE must be included. In both cases the number of "rows" is irrelevant, and omitted. If a function is already declared as accepting a pointer to a pointer, it is probably incorrect to pass a two-dimensional array directly to it. 19. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. Arrays of type T decay into pointers to type T, which is convenient; subscripting or incrementing the resultant pointer accesses the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally only useful when operating on multidimensional arrays, if at all. (See question 18 above.) When people speak casually of a pointer to an array, they usually mean a pointer to its first element; the type of this latter pointer is generally more useful. If you really need to declare a pointer to an entire array, use something like "int (*ap)[N];" where N is the size of the array. If the size of the array is unknown, N can be omitted, but the resulting type, "pointer to array of unknown size," is almost completely useless. (See also question 52.) 20. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." The resulting "ragged" array can save space, although it is not necessarily contiguous in memory as a real array would be. int **array = (int **)malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array[i] = (int *)malloc(ncolumns * sizeof(int)); (In "real" code, of course, each return value from malloc would have to be checked.) You can keep the array's contents contiguous, while making later reallocation of individual rows difficult, with a bit of explicit pointer arithmetic: int **array = (int **)malloc(nrows * sizeof(int *)); array[0] = (int *)malloc(nrows * ncolumns * sizeof(int)); for(i = 1; i < nrows; i++) array[i] = array[0] + i * ncolumns; In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: array[i][j]. If the double indirection implied by the above scheme is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array: int *array = (int *)malloc(nrows * ncolumns * sizeof(int)); However, you must now perform subscript calculations manually, accessing the i,jth element with array[i * ncolumns + j]. (A macro can hide the explicit calculation, but invoking it then requires parentheses and commas which don't look exactly like multidimensional array subscripts.) Section 3. Order of Evaluation 21. Under my compiler, the code int i = 7; printf("%d\n", i++ * i++); prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: Although the postincrement and postdecrement operators ++ and -- perform the operations after yielding the former value, many people misunderstand the implication of "after." It is _not_ guaranteed that the operation is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered "finished" (before the next "sequence point," in ANSI C's terminology). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards. The order of other embedded side effects is similarly undefined. For example, the expression i + (i = 2) may or may not have the value 4. The behavior of code which contains ambiguous or undefined side effects has always been undefined. (Note, too, that a compiler's choice, especially under ANSI rules, for "undefined behavior" may be to refuse to compile the code.) Don't even try to find out how your compiler implements such things (contrary to the ill-advised exercises in many C textbooks); as K&R wisely point out, "if you don't know _how_ they are done on various machines, the innocence may help to protect you." References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1. (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.) 22. But what about the &&, ||, and comma operators? I see code like "if((c = getchar()) == EOF || c == '\n')" ... A: There is a special exception for those operators, (as well as ?: ); each of them does imply a sequence point (i.e. left-to-right evaluation is guaranteed). Any book on C should make this clear. References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55, CT&P Sec. 3.7 pp. 46-7. Section 4. ANSI C 23. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, including several widespread public reviews, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardizes existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the much-lambasted trigraph sequences). The ANSI C standard also formalizes the C run-time library support routines. The published Standard includes a "Rationale," which explains many of its decisions, and discusses a number of subtle points, including several of those covered here. (The Rationale is "not part of ANSI Standard X3.159-1989, but is included for information only.") The Standard has also been adopted as ISO/IEC 9899:1990, although the Rationale is currently not included. 24. How can I get a copy of the ANSI C standard? A: Copies are available from American National Standards Institute 1430 Broadway New York, NY 10018 (212) 642-4900 or Global Engineering Documents 2805 McGaw Avenue Irvine, CA 92714 (714) 261-1455 (800) 854-7179 The cost from ANSI is $50.00, plus $6.00 shipping. Quantity discounts are available. (Note that ANSI derives revenues to support its operations from the sale of printed standards, so electronic copies are _not_ available.) 25. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. Check your nearest comp.sources archive. (See also questions 72 and 73.) 26. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". Old C (and ANSI C, in the absence of prototypes) silently promotes floats to doubles when passing them as arguments, and makes a corresponding silent change to formal parameter declarations, so the old-style definition actually says that func takes a double. The problem can be fixed either by using new-style syntax consistently in the definition: int func(float x) { ... } or by changing the new-style prototype declaration to match the old-style definition: extern int func(double); (In this case, it would be clearest to change the old-style definition to use double as well). Reference: ANSI Sec. 3.3.2.2 . 27. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which are neither under the control of the ANSI standard nor the C compiler developers on the systems which have them. The limitation is only that identifiers be _significant_ in the first six characters, not that they be restricted to six characters in length. This limitation is annoying, but certainly not unbearable, and is marked in the Standard as "obsolescent," i.e. a future revision will likely relax it. This concession to current, restrictive linkers really had to be made, no matter how vehemently some people oppose it. (The Rationale notes that its retention was "most painful.") If you disagree, or have thought of a trick by which a compiler burdened with a restrictive linker could present the C programmer with the appearance of more significance in external identifiers, read the excellently-worded X3.159 Rationale (see question 24), which discusses several such schemes and explains why they couldn't be mandated. References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale Sec. 3.1.2 pp. 19-21. Section 5. C Preprocessor 28. How can I write a macro to swap two values? A: There is no good answer to this question. If the values are integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers (and the "obvious" supercompressed implementation for integral types a^=b^=a^=b is, strictly speaking, illegal due to multiple side- effects; and it will not work if the two values are the same variable, and...). If the macro is intended to be used on values of arbitrary type (the usual goal), it cannot use a temporary, since it does not know what type of temporary it needs, and standard C does not provide a typeof operator. (GNU C does.) The best all-around solution is probably to forget about using a macro. If you're worried about the use of an ugly temporary, and know that your machine provides an exchange instruction, convince your compiler vendor to recognize the standard three-assignment swap idiom in the optimization phase. 29. I have some old code that tries to construct identifiers with a macro like #define Paste(a, b) a/**/b but it doesn't work any more. A: That comments disappeared entirely and could therefore be used for token pasting was an undocumented feature of some early preprocessor implementations, notably Reiser's. ANSI affirms (as did K&R) that comments are replaced with white space. However, since the need for pasting tokens was demonstrated and real, ANSI introduced a well- defined token-pasting operator, ##, which can be used like this: #define Paste(a, b) a##b Reference: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7. 30. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (note particularly that an apostrophe within a contracted word in a comment looks like the beginning of a character constant), and no newlines inside quotes. Therefore, natural-language comments should always be written between the "official" comment delimiters /* and */. References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37. 31. What's the best way to write a multi-statement cpp macro? A: The usual goal is to write a macro that can be invoked as if it were a single function-call statement. This means that the "caller" will be supplying the final semicolon, so the macro body should not. The macro body cannot be a simple brace-delineated compound statement, because syntax errors would result if it were invoked (apparently as a single statement, but with a resultant extra semicolon) as the if branch of an if/else statement with an explicit else clause. The traditional solution is to use #define Func() do { \ /* declarations */ \ stmt1; \ stmt2; \ /* ... */ \ } while(0) /* (no trailing ; ) */ When the "caller" appends a semicolon, this expansion becomes a single statement regardless of context. (An optimizing compiler will remove any "dead" tests or branches on the constant condition 0, although lint may complain.) If all of the statements in the intended macro are simple expressions, with no declarations, another technique is to separate them with commas and surround them with parentheses. Reference: CT&P Sec. 6.3 pp. 82-3. 32. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); The obvious disadvantage to this trick is that the caller must always remember to use the extra parentheses. (It is often best to use a bona-fide function, which can take a variable number of arguments in a well-defined way, rather than a macro. See questions 33 and 34 below.) Section 6. Variable-Length Argument Lists 33. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. Here is a function which concatenates an arbitrary number of strings into malloc'ed memory, using stdarg: #include <stddef.h> /* for NULL, size_t */ #include <stdarg.h> /* for va_ stuff */ #include <string.h> /* for strcat et al */ #include <stdlib.h> /* for malloc */ /* VARARGS1 */ char *vstrcat(char *first, ...) { size_t len = 0; char *retbuf; va_list argp; char *p; if(first == NULL) return NULL; len = strlen(first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) len += strlen(p); va_end(argp); retbuf = malloc(len + 1); /* +1 for trailing \0 */ if(retbuf == NULL) return NULL; /* error */ (void)strcpy(retbuf, first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) (void)strcat(retbuf, p); va_end(argp); return retbuf; } Usage is something like char *str = vstrcat("Hello, ", "world!", (char *)NULL); Note the cast on the last argument. (Also note that the caller must free the returned, malloc'ed storage.) Under a pre-ANSI compiler, rewrite the function definition without a prototype ("char *vstrcat(first) char *first; {"), #include <stdio.h> rather than <stddef.h>, replace "#include <stdlib.h>" with "extern char *malloc();", and use int instead of size_t. You may also have to delete the (void) casts, and use the older varargs package instead of stdarg. See the next question for hints. (If you know enough about your machine's architecture, it is possible to pick arguments off of the stack "by hand," but there is little reason to do so, since portable mechanisms exist. If you know how to access arguments "by hand," but have access to neither <stdarg.h> nor <varargs.h>, you could as easily implement one of them yourself, leaving your code portable.) References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 . 34. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. Here is an "error" routine which prints an error message, preceded by the string "error: " and terminated with a newline: #include <stdio.h> #include <stdarg.h> void error(char *fmt, ...) { va_list argp; fprintf(stderr, "error: "); va_start(argp, fmt); vfprintf(stderr, fmt, argp); va_end(argp); fprintf(stderr, "\n"); } To use varargs, instead of stdarg, change the function header to: void error(va_alist) va_dcl { char *fmt; change the va_start line to va_start(argp); and add the line fmt = va_arg(argp, char *); between the calls to va_start and vfprintf. (Note that there is no semicolon after va_dcl.) References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 . 35. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. You're on your own. 36. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Some systems have a nonstandard nargs() function available, but its use is questionable, since it typically returns the number of words pushed, not the number of arguments. (Floating point values and structures are usually passed as several words.) Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. printf-like functions do this by looking for formatting specifiers (%d and the like) in the format string (which is why these functions fail badly if the format string does not match the argument list). Another common technique (useful when the arguments are all of the same type) is to use a sentinel value (often 0, -1, or an appropriately-cast null pointer) at the end of the list (see the vstrcat and execl examples under questions 33 and 2 above). 37. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. You must provide a version of that other function which accepts a va_list pointer, as does vfprintf in the example above. If the arguments must be passed directly as actual arguments (not indirectly through a va_list pointer) to another function which is itself variadic (for which you do not have the option of creating an alternate, va_list-accepting version) no portable solution is possible. (The problem can be solved by resorting to machine-specific assembly language.) Section 7. Memory Allocation 38. Why doesn't this program work? main() { char *answer; printf("Type something:\n"); gets(answer); printf("You typed \"%s\"\n", answer); } A: The pointer variable "answer," which is handed to the gets function as the location into which the response should be stored, has not been set to point to any valid storage. It is an uninitialized variable, just as is the variable i in this example: main() { int i; printf("i = %d\n", i); } That is, we cannot say where the pointer "answer" points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that "answer" starts out as a null pointer.) The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation: #include <stdio.h> #include <string.h> main() { char answer[100], *p; printf("Type something:\n"); fgets(answer, 100, stdin); if((p = strchr(answer, '\n')) != NULL) *p = '\0'; printf("You typed \"%s\"\n", answer); } Note that this example also uses fgets instead of gets (always a good idea), so that the size of the array can be specified, so that fgets will not overwrite the end of the array if the user types an overly-long line. (Unfortunately, fgets does not automatically delete the trailing \n, as gets would.) It would also be possible to use malloc to allocate the answer buffer, and/or to parameterize its size (#define ANSWERSIZE 100). 39. I can't get strcat to work. I tried #include <string.h> main() { char *s1 = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); printf("%s\n", s3); } but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. C does not provide a true string type. C programmers use char *'s for strings, but must always keep allocation in mind. The compiler will only allocate memory for objects explicitly mentioned in the source code (in the case of "strings," this includes character arrays and string literals). The programmer must arrange (explicitly) for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or calling malloc. The simple strcat example could be fixed with something like char s1[20] = "Hello, "; char *s2 = "world!"; Note, however, that strcat appends the string pointed to by its second argument to that pointed to by the first, and merely returns its first argument, so the s3 variable is superfluous. Reference: CT&P Sec. 3.2 p. 32. 40. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. The Synopsis section at the top of a Unix-style man page can be misleading. The code fragments presented there are closer to the function definition used by the call's implementor than the invocation used by the caller. In particular, many routines accept pointers (e.g. to strings or structs), and the caller usually passes the address of some object (an array, or an entire struct). Another common example is stat(). 41. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages for malloc stated that the contents of freed memory was "left undisturbed;" this ill-advised guarantee is not universal and is not required by ANSI. Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list: struct list *listp, *nextp; for(listp = base; listp != NULL; listp = nextp) { nextp = listp->next; free((char *)listp); } and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer. References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10 p. 95. 42. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context. alloca cannot be written portably, and is difficult to implement on machines without a stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), stdin, 100). For these reasons, alloca cannot be used in programs which must be widely portable, no matter how useful it might be. Section 8. Structures 43. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: What K&R I said was that the restrictions on struct operations would be lifted in a forthcoming version of the compiler, and in fact struct assignment and passing were fully functional in Ritchie's compiler even as K&R I was being published. Although a few early C compilers lacked struct assignment, all modern compilers support it, and it is part of the ANSI C standard, so there should be no reluctance to use it. References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 . 44. How does struct passing and returning work? A: When structures are passed as arguments to functions, the entire struct is typically pushed on the stack, using as many words as are required. (Pointers to structures are often chosen precisely to avoid this overhead.) Structures are typically returned from functions in a location pointed to by an extra, "hidden" argument to the function. Older compilers often used a special, static location for structure returns, although this made struct-valued functions nonreentrant, which ANSI C disallows. Reference: ANSI Sec. 2.2.3 p. 13. 45. The following program works correctly, but it dumps core after it finishes. Why? struct list { char *item; struct list *next; } /* Here is the main program. */ main(argc, argv) ... A: A missing semicolon causes the compiler to believe that main returns a struct list. (The connection is hard to see because of the intervening comment.) When struct-valued functions are implemented by adding a hidden return pointer, the generated code tries to store a struct with respect to a pointer which was not actually passed (in this case, by the C start-up code). Attempting to store a structure into memory pointed to by the argc or argv value on the stack (where the compiler expected to find the hidden return pointer) causes the core dump. Reference: CT&P Sec. 2.3 pp. 21-2. 46. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. A byte- by-byte comparison could be invalidated by random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison would require unacceptable amounts of repetitive, in-line code for large structures. Either method would not necessarily "do the right thing" with pointer fields: oftentimes, equality should be judged by equality of the things pointed to rather than strict equality of the pointers themselves. If you want to compare two structures, you must write your own function to do so. C++ (among other languages) would let you arrange for the == operator to map to your function. References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Rationale Sec. 3.3.9 p. 47. 47. I came across some code that declared a structure like this: struct name { int namelen; char name[1]; }; and then did some tricky allocation to make the name array act like it had several elements. Is this legal and/or portable? A: This trick is popular, although Dennis Ritchie has called it "unwarranted chumminess with the compiler." It is surprisingly difficult to determine whether the ANSI C standard allows or disallows it, but it is hard to imagine a compiler or architecture for which it wouldn't work. (Debugging, array-bounds-checking compilers might issue warnings.) 48. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. If you don't have it, a suggested implementation is #define offsetof(type, mem) ((size_t) \ ((char *)&((type *) 0)->mem - (char *)((type *) 0))) This implementation is not 100% portable; some compilers may legitimately refuse to accept it. See the next question for a usage hint. Reference: ANSI Sec. 4.1.5 . 49. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is offsetb = offsetof(struct a, b) If structp is a pointer to an instance of this structure, and b is an int field with offset as computed above, b's value can be set indirectly with *(int *)((char *)structp + offsetb) = value; Section 9. Declarations 50. I can't seem to define a linked list node which contains a pointer to itself. I tried typedef struct { char *item; NODEPTR next; } NODE, *NODEPTR; but the compiler gave me error messages. Can't a struct in C contain a pointer to itself? A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. The problem is that the example above attempts to hide the struct pointer behind a typedef, which is not complete at the time it is used. First, rewrite it without a typedef: struct node { char *item; struct node *next; }; Then, if you wish to use typedefs, define them after the fact: typedef struct node NODE, *NODEPTR; Alternatively, define the typedefs first (using the line just above) and follow it with the full definition of struct node, which can then use the NODEPTR typedef for the "next" field. References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 . 51. How can I define a pair of mutually referential structures? I tried typedef struct { int structafield; STRUCTB *bpointer; } STRUCTA; typedef struct { int structbfield; STRUCTA *apointer; } STRUCTB; but the compiler doesn't know about STRUCTB when it is used in struct a. A: Again, the problem is not the pointers but the typedefs. First, define the two structures without using typedefs: struct a { int structafield; struct b *bpointer; }; struct b { int structbfield; struct a *apointer; }; The compiler can accept the field declaration struct b *bpointer within struct a, even though it has not yet heard of struct b. Occasionally it is necessary to precede this couplet with the empty declaration struct b; to mask the declarations (if in an inner scope) from a different struct b in an outer scope. Again, the typedefs could also be defined before, and then used within, the definitions for struct a and struct b. Problems arise only when an attempt is made to define and use a typedef within the same declaration. References: H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 . 52. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: This question can be answered in at least three ways (all assume the hypothetical array is to have 5 elements): 1. char *(*(*a[5])())(); 2. Build it up in stages, using typedefs: typedef char *cp; /* pointer to char */ typedef cp fpc(); /* function returning pointer to char */ typedef fpc *pfpc; /* pointer to above */ typedef pfpc fpfpc(); /* function returning... */ typedef fpfpc *pfpfpc; /* pointer to... */ pfpfpc a[5]; /* array of... */ 3. Use the cdecl program, which turns English into C and vice versa: $ cdecl cdecl> declare a as array 5 of pointer to function returning pointer to function returning pointer to char char *(*(*a[5])())() cdecl> cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions). Any good book on C should explain techniques for reading these complicated C declarations "inside out" to understand them ("declaration mimics use"). Reference: H&S Sec. 5.10.1 p. 116. 53. So where can I get cdecl? A: Several public-domain versions are available. One is in volume 14 of comp.sources.unix . (Commercial versions may also be available, at least one of which was shamelessly lifted from the public domain copy submitted by Graham Ross, one of cdecl's originators.) See question 73. Reference: K&R II Sec. 5.12 . 54. I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one? A: Use something like extern int func(); int (*fp)() = func; When the name of a function appears in an expression but is not being called (i.e. is not followed by a "("), it "decays" into a pointer (i.e. its address is implicitly taken), analagously to the implicit decay of an array into a pointer to its first element. An explicit extern declaration for the function is normally needed, since implicit external function declaration does not happen in this case (again, because the function name is not followed by a "("). 55. I've seen different methods used for calling through pointers to functions. What's the story? A: Originally, a pointer to a function had to be "turned into" a "real" function, with the * operator (and an extra pair of parentheses, to keep the precedence straight), before calling: int r, f(), (*fp)() = f; r = (*fp)(); Another analysis holds that functions are always called through pointers, but that "real" functions decay implicitly into pointers (in expressions, as they do in initializations) and so cause no trouble. This reasoning, which was adopted in the ANSI standard, means that r = fp(); is legal and works correctly, whether fp is a function or a pointer to one. (The usage has always been unambiguous; there is nothing you ever could have done with a function pointer followed by an argument list except call through it). An explicit * is harmless, and still allowed (and recommended, if portability to older compilers is important). References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41. Section 10. Boolean Expressions and Variables 56. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. (Using an int for a boolean may be faster, while using char will probably save data space.) The choice between #defines and enums is arbitrary and not terribly interesting. Use any of #define TRUE 1 #define YES 1 #define FALSE 0 #define NO 0 enum bool {false, true}; enum bool {no, yes}; or use raw 1 and 0, as long as you are consistent within one program or project. (The enum may be preferable if your debugger expands enum values when examining variables.) Some people prefer variants like #define TRUE (1==1) #define FALSE (!TRUE) or define "helper" macros such as #define Istrue(e) ((e) != 0) These don't buy anything (see below). 57. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test if((a == b) == TRUE) will work as expected (as long as TRUE is 1), but it is obviously silly. In general, explicit tests against TRUE and FALSE are undesirable, because some library functions (notably isupper, isalpha, etc.) return, on success, a nonzero value which is _not_ necessarily 1. (Besides, if you believe that "if((a == b) == TRUE)" is an improvement over "if(a == b)", why stop there? Why not use "if(((a == b) == TRUE) == TRUE)"?) A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable, or as the return value from a Boolean function, never in a comparison. Preprocessor macros like TRUE and FALSE (and, in fact, NULL) are used for code readability, not because the underlying values might ever change. That "true" is 1 and "false" (and source-code null pointers) 0 is guaranteed by the language. (See also question 8.) References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5 . 58. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. Although many people might have wished otherwise, the ANSI standard says that enumerations may be freely intermixed with integral types, without errors. (If such intermixing were disallowed without explicit casts, judicious use of enums could catch certain programming errors.) The advantages of enums are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enum variables are examined, and that a compiler may generate nonfatal warnings when enums and ints are indiscriminately mixed (such mixing can still be considered bad style even though it is not strictly illegal). References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 . Section 11. Operating System Dependencies 59. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. The delivery of characters from a "keyboard" to a C program is a function of the operating system in use, and cannot be standardized by the C language. If you are using curses, use its cbreak() function. Under UNIX, use ioctl to play with the terminal driver modes (CBREAK or RAW under "classic" versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or Posix systems). Under MS-DOS, use getch(). Under other operating systems, you're on your own. Beware that some operating systems make this sort of thing impossible, because character collection into input lines is done by peripheral processors not under direct control of the CPU running your program. Operating system specific questions are not appropriate for comp.lang.c . Many common questions are answered in frequently- asked questions postings in such groups as comp.unix.questions and comp.os.msdos.programmer . Note that the answers are often not unique even across different variants of Unix. Bear in mind when answering system-specific questions that the answer that applies to your system may not apply to everyone else's. References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1. 60. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. Some versions of curses have a nodelay() function. Depending on your system, you may also be able to use "nonblocking I/O", or a system call named "select", or the FIONREAD ioctl, or the O_NDELAY option to open() or fcntl(), or a kbhit() routine. 61. How can my program discover the complete pathname to the executable file from which it was invoked? A: Depending on the operating system, argv[0] may contain all or part of the pathname. (It may also contain nothing.) You may be able to duplicate the command language interpreter's search path logic to locate the executable if the name in argv[0] is incomplete. However, there is no guaranteed or portable solution. 62. How can a process change an environment variable in its caller? A: In general, it cannot. Different operating systems implement name/value functionality similar to the Unix environment in many different ways. Whether the "environment" can be usefully altered by a running program, and if so, how, is entirely system-dependent. Under Unix, a process can modify its own environment (some systems provide setenv() or putenv() functions to do this), and the modified environment is passed on to any child processes, but it is _not_ propagated back to the parent process. (The environment of the parent process can only be altered if the parent is explicitly set up to listen for some kind of change requests. The conventional execution of the BSD "tset" program in .profile and .login files effects such a scheme.) 63. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and some PC compilers supply chsize(), but there is no portable solution. Section 12. Stdio 64. Why does errno contain ENOTTY after a call to printf? A: Many implementations of the stdio package adjust their behavior slightly if stdout is a terminal. To make the determination, these implementations perform an operation which fails (with ENOTTY) if stdout is not a terminal. Although the output operation goes on to complete successfully, errno still contains ENOTTY. This behavior can be mildly confusing, but it is not strictly incorrect, because it is only meaningful for a program to inspect the contents of errno after an error has occurred (that is, after a library function that sets errno on error has returned an error code). Reference: CT&P Sec. 5.4 p. 73. 65. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. Several mechanisms attempt to perform the fflush for you, at the "right time," but they do not always work, particularly when stdout is a pipe rather than a terminal. 66. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. In particular, "\n" in a format string does not mean "expect a newline", it means "discard all whitespace". But the only way to discard all whitespace is to continue reading the stream until a non-whitespace character is seen (which is then left in the buffer for the next input), so the effect is that it keeps going until it sees a nonblank line. 67. So what should I use instead? A: You could use a "%c" format, which will read one character that you can then manually compare against a newline; or "%*c" and no variable if you're willing to trust the user to hit a newline; or "%*[^\n]%*c" to discard everything up to and including the newline. Usually the best solution is to use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Section 13. Miscellaneous 68. Can someone tell me how to write itoa (the inverse of atoi)? A: Just use sprintf. (You'll have to allocate space for the result somewhere anyway; see questions 38 and 39. Don't worry that sprintf may be overkill, potentially wasting run time or code space; it works well in practice.) 69. I know that the library routine localtime will convert a time_t into a broken-down struct tm, and that ctime will convert a time_t to a printable string. How can I perform the inverse operations of converting a struct tm or a string into a time_t? A: ANSI C specifies a library routine, mktime, which converts a struct tm to a time_t. Several public-domain versions of this routine are available in case your compiler does not support it yet. Converting a string to a time_t is harder, because of the wide variety of date and time formats which should be parsed. Public- domain routines have been written for performing this function, as well, but they are less likely to become standardized. References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI Sec. 4.12.2.3 . 70. How can I write data files which can be read on other machines with different word size, byte order, or floating point formats? A: The best solution is to use a text file (usually ASCII), written with fprintf and read with fscanf or the like. Be very skeptical of arguments which imply that text files are too big, or that reading and writing them is too slow. Not only is their efficiency frequently acceptable in practice, but the advantages of being able to manipulate them with standard tools can be overwhelming. If you must use a binary format, you can improve portability, and perhaps take advantage of prewritten I/O libraries, by making use of standardized formats such as Sun's XDR, OSI's ASN.1, or CCITT's X.409 . 71. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: Standard headers exist in part so that definitions appropriate to your compiler, operating system, and processor can be supplied. You cannot just pick up a copy of someone else's header file and expect it to work, unless that person is using exactly the same environment. Ask your compiler vendor why the file was not provided (or to send a replacement copy). 72. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available: p2c written by Dave Gillespie, and posted to comp.sources.unix in March, 1990 (Volume 21). ptoc another comp.sources.unix contribution, this one written in Pascal (comp.sources.unix, Volume 10, also patches in Volume 13?). f2c jointly developed by people from Bell Labs, Bellcore, and Carnegie Mellon. To find about f2c, send the mail message "send index from f2c" to netlib@research.att.com or research!netlib. FOR_C Available from: Cobalt Blue 2940 Union Ave., Suite C San Jose, CA 95124 (408) 723-0474 Promula.Fortran Available from Promula Development Corp. 3620 N. High St., Suite 301 Columbus, OH 43214 (614) 263-5454 The comp.sources.unix archives also contain converters between "K&R" C and ANSI C. 73. Where can I get copies of all these public-domain programs? A: If you have access to Usenet, see the regular postings in the comp.sources.unix and comp.sources.misc newsgroups, which describe, in some detail, the archiving policies and how to retrieve copies. The usual approach is to use anonymous ftp and/or uucp from a central, public-spirited site, such as uunet.uu.net. However, this article cannot track or list all of the available archive sites and how to access them. The comp.archives newsgroup contains numerous announcements of anonymous ftp availability of various items. 74. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? (And vice versa?) A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use, and may not be possible at all. Read your compiler documentation very carefully; sometimes there is a "mixed-language programming guide," although the techniques for passing arguments and ensuring correct run-time startup are often arcane. 75. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good, mostly because of the possibility of accidentally leaving comments unclosed by including the characters "/*" within them. For this reason, it is usually better to "comment out" large sections of code, which might contain comments, with #ifdef or #if 0. The character sequences /* and */ are not special within double- quoted strings, and do not therefore introduce comments, because a program (particularly one which is generating C code as output) might want to print them. It is hard to imagine why anyone would want or need to place a comment inside a quoted string. It is easy to imagine a program needing to print "/*". Reference: ANSI Rationale Sec. 3.1.9 p. 33. 76. My floating-point calculations are acting strangely and giving me different answers on different machines. A: Most digital computers use floating-point formats which provide a close but by no means exact simulation of real number arithmetic. Among other things, the associative and distributive laws do not hold completely (i.e. order of operation may be important, repeated addition is not necessarily equivalent to multiplication, and underflow or cumulative precision loss is often a problem). Don't assume that floating-point results will be exact, and especially don't assume that floating-point values can be compared for equality. (Don't stick in random "fuzz factors," either.) These problems are no worse for C than they are for any other computer language. Floating-point semantics are usually defined as "however the processor does them;" otherwise a compiler for a machine without the "right" model would have to do prohibitively expensive emulations. This article cannot begin to list the pitfalls associated with, and workarounds appropriate for, floating-point work. A good programming text should cover the basics. (Beware, though, that subtle problems can occupy numerical analysts for years.) References: K&P Sec. 6 pp. 115-8. 77. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C (and Ritchie's original PDP-11 compiler), leave out floating point support if it looks like it will not be needed. In particular, the non-floating- point versions of printf and scanf save space by not including code to handle %e, %f, and %g. It happens that Turbo C's heuristics for determining whether the program uses floating point are occasionally insufficient, and the programmer must insert one dummy explicit floating-point operation to force loading of floating-point support. Unfortunately, an apparently common sort of program (thus the frequency of the question) uses scanf to read, and/or printf to print, floating-point values upon which no arithmetic is done. In general, questions about a particular compiler are inappropriate for comp.lang.c . Problems with PC compilers, for instance, will find a more receptive audience in a PC newsgroup (e.g. comp.os.msdos.programmer). 78. Does anyone have a C compiler test suite I can use? A: Plum Hall (1 Spruce Ave., Cardiff, NJ 08232, USA), among others, sells one. 79. Where can I get a YACC grammar for C? A: The definitive grammar is of course the one in the ANSI standard. Several copies are floating around; keep your eyes open. There is one on uunet.uu.net (192.48.96.2) in net.sources/ansi.c.grammar.Z . FSF's GNU C compiler contains a grammar, as does the appendix to K&R II. References: ANSI Sec. A.2 . 80. What's the best style for code layout in C? A: K&R, while providing the example most often copied, also supply a good excuse for avoiding it: The position of braces is less important; we have chosen one of several popular styles. Pick a style that suits you, then use it consistently. It is more important that the layout chosen be consistent (with itself, and with nearby or common code) than that it be "perfect." If your coding environment (i.e. local custom or company policy) does not suggest a style, and you don't feel like inventing your own, just copy K&R. (The tradeoffs between various indenting and brace placement options can be exhaustively and minutely examined, but don't warrant repetition here. See also the Indian Hill Style Guide.) Reference: K&R I Sec. 1.2 p. 10. 81. Where can I get the "Indian Hill Style Guide" and other coding standards? A: Various documents are available for anonymous ftp from: Site: File or directory: cs.washington.edu ~ftp/pub/cstyle.tar.Z (128.95.1.4) (the updated Indian Hill guide) cs.toronto.edu doc/programming giza.cis.ohio-state.edu pub/style-guide prep.ai.mit.edu pub/gnu/standards.text 82. How do you pronounce "char"? What's that funny name for the "#" character? A: You can pronounce the C keyword "char" like the English words "char," "care," or "car;" the choice is arbitrary. Bell Labs once proposed the (now obsolete) term "octothorpe" for the "#" character. Trivia questions like these aren't any more pertinent for comp.lang.c than they are for any of the other groups they frequently come up in. The "jargon file" (also published as _The Hacker's Dictionary_) contains lots of tidbits like these, as does the official Usenet ASCII pronunciation list, maintained by Maarten Litmaath. (The pronunciation list also appears in the jargon file under ASCII, as well as in the comp.unix frequently-asked questions list.) 83. Where can I get extra copies of this list? What about back issues? A: For now, just pull it off the net; it is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Eventually, it may be available for anonymous ftp, or via a mailserver. (Note that the size of the list is monotonically increasing; older copies are obsolete and don't contain much, except the occasional typo, that the current list doesn't.) Bibliography ANSI American National Standard for Information Systems -- Programming Language -- C, ANSI X3.159-1989. H&S Samuel P. Harbison and Guy L. Steele, C: A Reference Manual, Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0. (A third edition has recently been released.) PCS Mark R. Horton, Portable C Software, Prentice Hall, 1990, ISBN 0-13-868050-7. K&P Brian W. Kernighan and P.J. Plaugher, The Elements of Programming Style, Second Edition, McGraw-Hill, 1978, ISBN 0- 07-034207-5. K&R I Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall, 1978, ISBN 0-13-110163-3. K&R II Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Second Edition, Prentice Hall, 1988, ISBN 0-13- 110362-8, 0-13-110370-9. CT&P Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989, ISBN 0-201-17928-8. There is a more extensive bibliography in the revised Indian Hill style guide (see question 81). Acknowledgements Thanks to Sudheer Apte, Mark Brader, Joe Buehler, Raymond Chen, Christopher Calabrese, Norm Diamond, Ray Dunn, Stephen M. Dunn, Bjorn Engsig, Doug Gwyn, Tony Hansen, Joe Harrington, Guy Harris, Karl Heuer, Blair Houghton, Kirk Johnson, Andrew Koenig, John Lauro, Christopher Lott, Evan Manning, Mark Moraes, Francois Pinard, randall@virginia, Rich Salz, Paul Sand, Patricia Shanahan, Joshua Simons, Henry Spencer, Erik Talvola, Clarke Thatcher, Chris Torek, Ed Vielmetti, and Freek Wiedijk, who have contributed, directly or indirectly, to this article. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained. The C code in this article (vstrcat, error, etc.) is public domain and may be used without restriction.
scs@adam.mit.edu (Steve Summit) (01/15/91)
[Last modified December 16, 1990 by scs.] This article contains minimal answers to the comp.lang.c frequently- asked questions list. Please see the long version (posted on the first of each month) for more detailed explanations and references. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic function calls) a constant 0 with an appropriate explicit cast is required. 3. But aren't pointers the same as ints? A: Not since the early days. 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0), which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. I use the preprocessor macro "#define Nullptr(type) (type *)0 " to help me build null pointers of the correct type. A: This trick does not buy much. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 9. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler was broken. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. 14. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." Section 2. Arrays and Pointers 15. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. Use extern char a[]. 16. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. Otherwise, the two forms are not interchangeable. 17. So what is meant by the "equivalence of pointers and arrays" in C? A: Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the fact that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. 18. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 19. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. 20. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Section 3. Order of Evaluation 21. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++); " prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 22. But what about the &&, ||, and comma operators? A: There is a special exception for those operators, (as well as ?: ); left-to-right evaluation is guaranteed. Section 4. ANSI C 23. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. 24. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for addresses. 25. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. 26. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed by using either new-style (prototype) or old-style syntax consistently. 27. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which cannot be forced (by mere words in a Standard) to upgrade. Section 5. C Preprocessor 28. How can I write a macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 29. I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b ", but it doesn't work any more. A: Use the ANSI token-pasting operator ##. 30. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (i.e. no single apostrophes), and no newlines inside quotes. 31. What's the best way to write a multi-statement cpp macro? A: #define Func() do {stmt1; stmt2; ... } while(0) /* (no trailing ;) */ 32. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Section 6. Variable-Length Argument Lists 33. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. 34. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 35. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 36. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 37. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Section 7. Memory Allocation 38. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 39. I can't get strcat to work. I tried "char *s1 = "Hello, ", *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. 40. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. 41. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 42. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. Section 8. Structures 43. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 44. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 45. I have a program which works correctly, but dumps core after it finishes. Why? A: Check to see if a structure declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. 46. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 47. I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make the array act like it had several elements. Is this legal and/or portable? A: It is surprisingly difficult to determine whether the ANSI C standard allows or disallows it. 48. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 49. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Section 9. Declarations 50. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 51. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. 52. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: char *(*(*a[5])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 53. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. 54. How do I initialize a pointer to a function? A: Use something like "extern int func(); int (*fp)() = func; " . 55. I've seen different methods used for calling through pointers to functions. A: The extra parentheses and explicit * are now officially optional, although "Classic C" required them. Section 10. Boolean Expressions and Variables 56. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 57. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 58. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enumerations are compatible with integral types. Section 11. Operating System Dependencies 59. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 60. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 61. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 62. How can a process change an environment variable in its caller? A: In general, it cannot. 63. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and some PC compilers supply chsize(), but there is no portable solution. Section 12. Stdio 64. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 65. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. 66. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 67. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. Section 13. Miscellaneous 68. Can someone tell me how to write itoa? A: Just use sprintf. 69. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 70. How can I write data files which can be read on other machines with different data formats? A: The best solution is to use a text file. 71. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 72. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 73. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups for information. 74. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 75. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 76. My floating-point calculations are acting strangely and giving me different answers on different machines. A: See the full list for a brief explanation, or any good programming book for a better one. 77. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 78. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 79. Where can I get a YACC grammar for C? A: See the unabridged list. 80. What's the best style for code layout in C? A: There is no one "best style," but see the full list for a few suggestions. 81. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. 82. How do you pronounce "char"? What's that funny name for the "#" character? A: Like the English words "char," "care," or "car" (your choice); "octothorpe." 83. Where can I get extra copies of this list? A: For now, just pull it off the net; the unabridged version is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (02/06/91)
[Last modified February 5, 1990 by scs.] Certain topics come up again and again on this newsgroup. They are good questions, and the answers may not be immediately obvious, but each time they recur, much net bandwidth and reader time is wasted on repetitive responses, and on tedious corrections to the incorrect answers which are inevitably posted. This article, which is posted monthly, attempts to answer these common questions definitively and succinctly, so that net discussion can move on to more constructive topics without continual regression to first principles. This article does not, and cannot, provide an exhaustive discussion of every subtle point and counterargument which could be mentioned with respect to these topics. Cross-references to standard C publications have been provided, for further study by the interested and dedicated reader. A few of the more perplexing and pervasive topics may be further explored in some in-depth minitreatises posted in conjunction with this article. No mere newsgroup article can substitute for thoughtful perusal of a full-length language reference manual. Anyone interested enough in C to be following this newsgroup should also be interested enough to read and study one or more such manuals, preferably several times. Some vendors' compiler manuals are unfortunately inadequate; a few even perpetuate some of the myths which this article attempts to debunk. Several noteworthy books on C are listed in this article's bibliography. If you have a question about C which is not answered in this article, please try to answer it by checking a few of the referenced books, or by asking knowledgeable colleagues, before posing your question to the net at large. There are many people on the net who are happy to answer questions, but the volume of repetitive answers posted to one question, as well as the growing numbers of questions as the net attracts more readers, can become oppressive. If you have questions or comments prompted by this article, please reply by mail rather than following up -- this article is meant to decrease net traffic, not increase it. This article is always being improved. Your input is welcomed. Send your comments to scs@adam.mit.edu, scs%adam.mit.edu@mit.edu, and/or mit-eddie!adam!scs; this article's From: line may be unusable. The questions answered here are divided into several categories: 1. Null Pointers 2. Arrays and Pointers 3. Order of Evaluation 4. ANSI C 5. C Preprocessor 6. Variable-Length Argument Lists 7. Lint 8. Memory Allocation 9. Structures 10. Declarations 11. Boolean Expressions and Variables 12. Operating System Dependencies 13. Stdio 14. Style 15. Miscellaneous Herewith, some frequently-asked questions and their answers: Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: The language definition states that for each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. That is, the address-of operator & will never yield a null pointer, nor will a successful call to malloc. (malloc returns a null pointer when it fails, and this is a typical use of null pointers: as a "special" pointer value with some other meaning, usually "not allocated" or "not pointing anywhere yet.") A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere (that is, at some random object, or at a garbage or unallocated address). See also question 43. As mentioned in the definition above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different. Although programmers need not know the internal values, the compiler must always be informed which type of null pointer is required, so it can make the distinction if necessary (see below). References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38. 2. How do I "get" a null pointer in my programs? A: According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal: char *p = 0; if(p != 0) However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. For instance, the Unix system call "execl" takes a variable-length, null-pointer- terminated list of character pointer arguments. To generate a null pointer in a function call context, an explicit cast is typically required: execl("/bin/sh", "sh", "-c", "ls", (char *)0); If the (char *) cast were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong.) When function prototypes are in scope, argument passing becomes an "assignment context," and casts may safely be omitted, since the prototype tells the compiler that a pointer is required, and of which type, enabling it to correctly cast unadorned 0's. Function prototypes cannot provide the types for variable arguments in variable-length argument lists, however, so explicit casts are still required for those arguments. It is safest always to cast null pointer function arguments, to guard against varargs functions or those without prototypes, to allow interim use of non-ANSI compilers, and to demonstrate that you know what you are doing. Summary: Unadorned 0 okay: Explicit cast required: initialization function call, no prototype in scope assignments variable argument to comparisons varargs function function call, prototype in scope, fixed argument References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI Sec. 3.2.2.3 . 3. But aren't pointers the same as ints? A: Not since the early days. Attempting to turn pointers into integers, or to build pointers out of integers, has always been machine-dependent and unportable, and doing so is strongly discouraged. (Any object pointer may be cast to the "universal" pointer type void *, or char * under a pre-ANSI compiler, when heterogeneous pointers must be passed around.) References: K&R I Sec. 5.6 pp. 102-3; ANSI Sec. 3.2.2.3 p. 37, Sec. 3.3.4 pp. 46-7. 4. What is NULL and how is it #defined? A: As a stylistic convention, many people prefer not to have unadorned 0's scattered throughout their programs. For this reason, the preprocessor macro NULL is #defined (by <stdio.h> or <stddef.h>), with value 0 (or (void *)0, about which more later). A programmer who wishes to make explicit the distinction between 0 the integer and 0 the null pointer can then use NULL whenever a null pointer is required. This is a stylistic convention only; the preprocessor turns NULL back to 0 which is then recognized by the compiler (in pointer contexts) as before. In particular, a cast may still be necessary before NULL (as before 0) in a function call argument. (The table under question 2 above applies for NULL as well as 0.) NULL should _only_ be used for pointers. It should not be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (ANSI allows the #definition of NULL to be (void *)0, which will not work in non- pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition #define NUL '\0' if you must. References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38, Rationale Sec. 4.1.5 p. 74. 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: Programmers should never need to know the internal representation(s) of null pointers, because they are normally taken care of by the compiler. If a machine uses a nonzero bit pattern for null pointers, it is the compiler's responsibility to generate it when the programmer requests, by writing "0" or "NULL," a null pointer. Therefore, #defining NULL as 0 on a machine for which internal null pointers are nonzero is as valid as on any other, because the compiler must (and can) still generate the machine's correct null pointers in response to unadorned 0's seen in pointer contexts. 6. If NULL were defined as follows: #define NULL (char *)0 wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. The suggested #definition would make uncast NULL arguments to functions expecting pointers to characters to work correctly, but pointer arguments to other types would still be problematical, and legal constructions such as FILE *fp = NULL; could fail. Nevertheless, ANSI C allows the alternate #define NULL (void *)0 definition for NULL. Besides helping incorrect programs to work (but only on machines with all pointers the same, thus questionably valid assistance) this definition may catch programs which use NULL incorrectly (e.g. when the ASCII NUL character was really intended). 7. I use the preprocessor macro #define Nullptr(type) (type *)0 to help me build null pointers of the correct type. A: This trick, though popular with beginning programmers, does not buy much. It is not needed in assignments and comparisons; see question 2. It does not even save keystrokes. Its use suggests to the reader that the author is shaky on the subject of null pointers, and requires the reader to check the #definition of the macro, its invocations, and _all_ other pointer usages much more carefully. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: When C requires the boolean value of an expression (in the if, while, for, and do statements, and with the &&, ||, !, and ?: operators), a false value is produced when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes if(expr) where "expr" is any expression at all, the compiler essentially acts as if it had been written as if(expr != 0) Substituting the trivial pointer expression "p" for "expr," we have if(p) is equivalent to if(p != 0) and this is a comparison context, so the compiler can tell that the (implicit) 0 is a null pointer, and use the correct value. There is no trickery involved here; compilers do work this way, and generate identical code for both statements. The internal representation of a pointer does _not_ matter. The boolean negation operator, !, can be described as follows: !expr is essentially equivalent to expr?0:1 It is left as an exercise for the reader to show that if(!p) is equivalent to if(p == 0) See also question 62. References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and 3.6.5 . 9. If "NULL" and "0" are equivalent, which should I use? A: Many programmers believe that "NULL" should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding "NULL" and "0" is only compounded by hiding "0" behind a #definition, and prefer to use unadorned "0" instead. There is no one right answer. C programmers must understand that "NULL" and "0" are interchangeable and that an uncast "0" is perfectly acceptable in initialization, assignment, and comparison contexts. Any usage of "NULL" (as opposed to "0") should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's. Again, NULL should not be used for other than pointers. Reference: K&R II Sec. 5.4 p. 102. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. Although preprocessor macros are often used in place of numbers because the numbers might change, this is _not_ the reason that NULL is used in place of 0. The language guarantees that source-code 0's (in pointer contexts) generate null pointers. NULL is used only as a stylistic convention. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler was broken. In general, making decisions about a language based on the behavior of one particular compiler is likely to be counterproductive. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. (On some machines the internal value is all-bits-0; on others it is not.) A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). When the term "null" or "NULL" is casually used, one of several things may be meant: 1. The conceptual null pointer, the abstract language concept defined in question 1. It is implemented with... 2. The internal (or run-time) representation of a null pointer, which may or may not be all-bits-0 and which may be different for different pointer types. The actual values should be of concern only to compiler writers. Authors of C programs never see them, since they use... 3. The source code syntax for null pointers, which is the single character "0". It is often hidden behind... 4. The NULL macro, which is #defined to be "0" or "(void *)0". Finally, as a red herring, we have... 5. The ASCII null character (NUL), which does have all bits zero, but has no relation to the null pointer except in name. This article always uses the phrase "null pointer" for sense 1, the character "0" for sense 3, and the capitalized word "NULL" for sense 4. 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: C programmers traditionally like to know more than they need to about the underlying machine implementation. The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. The construct "if(p == 0)" is easily misread as calling for conversion of p to an integral type, rather than 0 to a pointer type, before the comparison. Finally, the distinction between the several uses of the term "null" (listed above) is often overlooked. One good way to wade out of the confusion is to imagine that C had a keyword (perhaps "nil", like Pascal) with which null pointers were requested. The compiler could either turn "nil" into the correct type of null pointer, when it could determine the type from the source code (as it does with 0's in reality), or complain when it could not. Now, in fact, in C the keyword for a null pointer is not "nil" but "0", which works almost as well, except that an uncast "0" in a non-pointer context generates an integer zero instead of an error message, and if that uncast 0 was supposed to be a null pointer, the code may not work. 14. I'm still confused. I just can't understand all this null pointer stuff. A: Follow these two simple rules: 1. When you want to refer to a null pointer in source code, use "0" or "NULL". 2. If the usage of "0" or "NULL" is an argument in a function call, cast it to the pointer type expected by the function being called. The rest of the discussion has to do with other people's misunderstandings, or with the internal representation of null pointers, which you shouldn't need to know. Understand questions 1, 2, and 4, and consider 9 and 13, and you'll do fine. Section 2. Arrays and Pointers 15. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. The type "pointer-to-type-T" is not the same as "array-of-type-T." Use extern char a[]. References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5. 16. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. This identity is related to the fact that arrays "decay" into pointers in expressions. That is, when an array name is mentioned in an expression, it is converted immediately into a pointer to the array's first element. Therefore, an array is never passed to a function; rather a pointer to its first element is passed instead. Allowing pointer parameters to be declared as arrays is a simply a way of making it look as though the array was actually being passed. Some programmers prefer, as a matter of style, to use this syntax to indicate that the pointer parameter is expected to point to the start of an array rather than to some single value. Since functions can never receive arrays as parameters, any parameter declarations which "look like" arrays, e.g. f(a) char a[]; are treated as if they were pointers, since that is what the function will receive if an array is passed: f(a) char *a; To repeat, however, this conversion holds only within function formal parameter declarations, nowhere else. If this conversion bothers you, don't use it; many people have concluded that the confusion it causes outweighs the small advantage of having the declaration "look like" the call and/or the uses within the function. References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3 pp. 33-4. 17. So what is meant by the "equivalence of pointers and arrays" in C? A: Much of the confusion surrounding pointers in C can be traced to a misunderstanding of this statement. Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. (The fact that, as formal parameters to functions, array-style and pointer-style declarations are in fact interchangeable does nothing to reduce the confusion.) "Equivalence" refers to the fact (mentioned above) that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. That is, if we have char a[10]; char *p = a; int i; we can refer to a[i] and p[i]. (That pointers can be subscripted like arrays is hardly surprising, since arrays have decayed into pointers by the time they are subscripted.) References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec. 5.4.1 p. 93; ANSI Sec. 3.3.2.1, Sec. 3.3.6 . 18. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? A: Yes, Virginia, array subscripting is commutative in C. This curious fact follows from the pointer definition of array subscripting, namely that a[e] is exactly equivalent to *((a)+(e)), for _any_ expression e and primary expression a, as long as one of them is a pointer expression. This unsuspected commutativity is often mentioned in C texts as if it were something to be proud of, but it finds no useful application outside of the Obfuscated C Contest (see also question 83). 19. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays are confusing, and it is best to avoid them. (The confusion is heightened by the existence of incorrect compilers, including some versions of pcc and pcc-derived lint's, which improperly accept assignments of multi-dimensional arrays to multi-level pointers.) If you are passing a two-dimensional array to a function: int array[YSIZE][XSIZE]; f(array); the function's declaration should match: f(int a[][XSIZE]) {...} or f(int (*ap)[XSIZE]) {...} /* ap is a pointer to an array */ In the first declaration, the compiler performs the usual implicit rewriting of "array of array" to "pointer to array;" in the second form the pointer declaration is explicit. The called function does not care how big the array is, but it must know its shape, so the "column" dimension XSIZE must be included. In both cases the number of "rows" is irrelevant, and omitted. If a function is already declared as accepting a pointer to a pointer, it is probably incorrect to pass a two-dimensional array directly to it. 20. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. Arrays of type T decay into pointers to type T, which is convenient; subscripting or incrementing the resultant pointer accesses the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally only useful when operating on multidimensional arrays, if at all. (See question 19 above.) When people speak casually of a pointer to an array, they usually mean a pointer to its first element; the type of this latter pointer is generally more useful. If you really need to declare a pointer to an entire array, use something like "int (*ap)[N];" where N is the size of the array. If the size of the array is unknown, N can be omitted, but the resulting type, "pointer to array of unknown size," is almost completely useless. (See also question 57.) 21. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." The resulting "ragged" array can save space, although it is not necessarily contiguous in memory as a real array would be. int **array = (int **)malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array[i] = (int *)malloc(ncolumns * sizeof(int)); (In "real" code, of course, each return value from malloc would have to be checked.) You can keep the array's contents contiguous, while making later reallocation of individual rows difficult, with a bit of explicit pointer arithmetic: int **array = (int **)malloc(nrows * sizeof(int *)); array[0] = (int *)malloc(nrows * ncolumns * sizeof(int)); for(i = 1; i < nrows; i++) array[i] = array[0] + i * ncolumns; In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: array[i][j]. If the double indirection implied by the above scheme is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array: int *array = (int *)malloc(nrows * ncolumns * sizeof(int)); However, you must now perform subscript calculations manually, accessing the i,jth element with array[i * ncolumns + j]. (A macro can hide the explicit calculation, but invoking it then requires parentheses and commas which don't look exactly like multidimensional array subscripts.) Section 3. Order of Evaluation 22. Under my compiler, the code int i = 7; printf("%d\n", i++ * i++); prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: Although the postincrement and postdecrement operators ++ and -- perform the operations after yielding the former value, many people misunderstand the implication of "after." It is _not_ guaranteed that the operation is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered "finished" (before the next "sequence point," in ANSI C's terminology). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards. The order of other embedded side effects is similarly undefined. For example, the expression i + (i = 2) may or may not have the value 4. The behavior of code which contains ambiguous or undefined side effects has always been undefined. (Note, too, that a compiler's choice, especially under ANSI rules, for "undefined behavior" may be to refuse to compile the code.) Don't even try to find out how your compiler implements such things (contrary to the ill-advised exercises in many C textbooks); as K&R wisely point out, "if you don't know _how_ they are done on various machines, the innocence may help to protect you." References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1. (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.) 23. But what about the &&, ||, and comma operators? I see code like "if((c = getchar()) == EOF || c == '\n')" ... A: There is a special exception for those operators, (as well as ?: ); each of them does imply a sequence point (i.e. left-to-right evaluation is guaranteed). Any book on C should make this clear. References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55, CT&P Sec. 3.7 pp. 46-7. Section 4. ANSI C 24. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, including several widespread public reviews, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardizes existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the much-lambasted trigraph sequences). The ANSI C standard also formalizes the C run-time library support routines. The published Standard includes a "Rationale," which explains many of its decisions, and discusses a number of subtle points, including several of those covered here. (The Rationale is "not part of ANSI Standard X3.159-1989, but is included for information only.") The Standard has also been adopted as an international standard, ISO/IEC 9899:1990, although the Rationale is currently not included. 25. How can I get a copy of the ANSI C standard? A: Copies are available from American National Standards Institute 1430 Broadway New York, NY 10018 USA (+1) 212 642 4900 or Global Engineering Documents 2805 McGaw Avenue Irvine, CA 92714 USA (+1) 714 261 1455 (800) 854 7179 (U.S. & Canada) The cost from ANSI is $50.00, plus $6.00 shipping. Quantity discounts are available. (Note that ANSI derives revenues to support its operations from the sale of printed standards, so electronic copies are _not_ available.) 26. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. Check your nearest comp.sources archive. (See also questions 81 and 82.) 27. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". Old C (and ANSI C, in the absence of prototypes) silently promotes floats to doubles when passing them as arguments, and makes a corresponding silent change to formal parameter declarations, so the old-style definition actually says that func takes a double. The problem can be fixed either by using new-style syntax consistently in the definition: int func(float x) { ... } or by changing the new-style prototype declaration to match the old-style definition: extern int func(double); (In this case, it would be clearest to change the old-style definition to use double as well). Reference: ANSI Sec. 3.3.2.2 . 28. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which are neither under the control of the ANSI standard nor the C compiler developers on the systems which have them. The limitation is only that identifiers be _significant_ in the first six characters, not that they be restricted to six characters in length. This limitation is annoying, but certainly not unbearable, and is marked in the Standard as "obsolescent," i.e. a future revision will likely relax it. This concession to current, restrictive linkers really had to be made, no matter how vehemently some people oppose it. (The Rationale notes that its retention was "most painful.") If you disagree, or have thought of a trick by which a compiler burdened with a restrictive linker could present the C programmer with the appearance of more significance in external identifiers, read the excellently-worded X3.159 Rationale (see question 25), which discusses several such schemes and explains why they couldn't be mandated. References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale Sec. 3.1.2 pp. 19-21. Section 5. C Preprocessor 29. How can I write a macro to swap two values? A: There is no good answer to this question. If the values are integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers (and the "obvious" supercompressed implementation for integral types a^=b^=a^=b is, strictly speaking, illegal due to multiple side- effects; and it will not work if the two values are the same variable, and...). If the macro is intended to be used on values of arbitrary type (the usual goal), it cannot use a temporary, since it does not know what type of temporary it needs, and standard C does not provide a typeof operator. (GNU C does.) The best all-around solution is probably to forget about using a macro. If you're worried about the use of an ugly temporary, and know that your machine provides an exchange instruction, convince your compiler vendor to recognize the standard three-assignment swap idiom in the optimization phase. 30. I have some old code that tries to construct identifiers with a macro like #define Paste(a, b) a/**/b but it doesn't work any more. A: That comments disappeared entirely and could therefore be used for token pasting was an undocumented feature of some early preprocessor implementations, notably Reiser's. ANSI affirms (as did K&R) that comments are replaced with white space. However, since the need for pasting tokens was demonstrated and real, ANSI introduced a well- defined token-pasting operator, ##, which can be used like this: #define Paste(a, b) a##b Reference: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7. 31. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (note particularly that an apostrophe within a contracted word in a comment looks like the beginning of a character constant), and no newlines inside quotes. Therefore, natural-language comments should always be written between the "official" comment delimiters /* and */. References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37. 32. What's the best way to write a multi-statement cpp macro? A: The usual goal is to write a macro that can be invoked as if it were a single function-call statement. This means that the "caller" will be supplying the final semicolon, so the macro body should not. The macro body cannot be a simple brace-delineated compound statement, because syntax errors would result if it were invoked (apparently as a single statement, but with a resultant extra semicolon) as the if branch of an if/else statement with an explicit else clause. The traditional solution is to use #define Func() do { \ /* declarations */ \ stmt1; \ stmt2; \ /* ... */ \ } while(0) /* (no trailing ; ) */ When the "caller" appends a semicolon, this expansion becomes a single statement regardless of context. (An optimizing compiler will remove any "dead" tests or branches on the constant condition 0, although lint may complain.) If all of the statements in the intended macro are simple expressions, with no declarations, another technique is to separate them with commas and surround them with parentheses. Reference: CT&P Sec. 6.3 pp. 82-3. 33. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); The obvious disadvantage to this trick is that the caller must always remember to use the extra parentheses. (It is often best to use a bona-fide function, which can take a variable number of arguments in a well-defined way, rather than a macro. See questions 34 and 35 below.) Section 6. Variable-Length Argument Lists 34. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. Here is a function which concatenates an arbitrary number of strings into malloc'ed memory, using stdarg: #include <stddef.h> /* for NULL, size_t */ #include <stdarg.h> /* for va_ stuff */ #include <string.h> /* for strcat et al */ #include <stdlib.h> /* for malloc */ /* VARARGS1 */ char *vstrcat(char *first, ...) { size_t len = 0; char *retbuf; va_list argp; char *p; if(first == NULL) return NULL; len = strlen(first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) len += strlen(p); va_end(argp); retbuf = malloc(len + 1); /* +1 for trailing \0 */ if(retbuf == NULL) return NULL; /* error */ (void)strcpy(retbuf, first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) (void)strcat(retbuf, p); va_end(argp); return retbuf; } Usage is something like char *str = vstrcat("Hello, ", "world!", (char *)NULL); Note the cast on the last argument. (Also note that the caller must free the returned, malloc'ed storage.) Under a pre-ANSI compiler, rewrite the function definition without a prototype ("char *vstrcat(first) char *first; {"), #include <stdio.h> rather than <stddef.h>, replace "#include <stdlib.h>" with "extern char *malloc();", and use int instead of size_t. You may also have to delete the (void) casts, and use the older varargs package instead of stdarg. See the next question for hints. (If you know enough about your machine's architecture, it is possible to pick arguments off of the stack "by hand," but there is little reason to do so, since portable mechanisms exist. If you know how to access arguments "by hand," but have access to neither <stdarg.h> nor <varargs.h>, you could as easily implement one of them yourself, leaving your code portable.) References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 . 35. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. Here is an "error" routine which prints an error message, preceded by the string "error: " and terminated with a newline: #include <stdio.h> #include <stdarg.h> void error(char *fmt, ...) { va_list argp; fprintf(stderr, "error: "); va_start(argp, fmt); vfprintf(stderr, fmt, argp); va_end(argp); fprintf(stderr, "\n"); } To use varargs, instead of stdarg, change the function header to: void error(va_alist) va_dcl { char *fmt; change the va_start line to va_start(argp); and add the line fmt = va_arg(argp, char *); between the calls to va_start and vfprintf. (Note that there is no semicolon after va_dcl.) References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 . 36. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. You're on your own. 37. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Some systems have a nonstandard nargs() function available, but its use is questionable, since it typically returns the number of words pushed, not the number of arguments. (Floating point values and structures are usually passed as several words.) Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. printf-like functions do this by looking for formatting specifiers (%d and the like) in the format string (which is why these functions fail badly if the format string does not match the argument list). Another common technique (useful when the arguments are all of the same type) is to use a sentinel value (often 0, -1, or an appropriately-cast null pointer) at the end of the list (see the vstrcat and execl examples under questions 34 and 2 above). 38. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. You must provide a version of that other function which accepts a va_list pointer, as does vfprintf in the example above. If the arguments must be passed directly as actual arguments (not indirectly through a va_list pointer) to another function which is itself variadic (for which you do not have the option of creating an alternate, va_list-accepting version) no portable solution is possible. (The problem can be solved by resorting to machine-specific assembly language.) Section 7. Lint 39. I just typed in this program, and it's acting strangely. Can you see anything wrong with it? A: Try running lint first. Most C compilers are really only half- compilers, electing not to diagnose numerous source code difficulties which would not actively preclude code generation. That the "other half," better error detection, was deferred to lint, was a fairly deliberate decision on the part of the earliest Unix C compiler authors, but is inexcusable (in the absence of a supplied, consistent lint) in a modern compiler. 40. How can I shut off the "warning: possible pointer alignment problem" message lint gives me for each call to malloc? A: The problem is that traditional versions of lint do not know, and cannot be told, that malloc "returns a pointer to space suitably aligned for storage of any type of object." It is possible to provide a pseudoimplementation of malloc, using a #define inside of #ifdef lint, which effectively shuts this warning off, but a simpleminded #definition will also suppress meaningful messages about truly incorrect invocations. It may be easier simply to ignore the message, perhaps in an automated way with grep -v. 41. Where can I get an ANSI-compatible lint? A: A product called FlexeLint is available (in "shrouded source form," for compilation on 'most any system) from Gimpel Software 3207 Hogarth Lane Collegeville, PA 19426 USA (+1) 215 584 4261 Another product is MKS lint, from Mortice Kern Systems. At the moment, I don't have their address, but you can send email to inquiry@mks.com . 42. Don't ANSI function prototypes render lint obsolete? A: No. First of all, prototypes work well only if the programmer works assiduously to maintain them, and the effort to do so (plus the extra recompilations required by numerous, more-frequently-modified header files) can rival the toil of keeping function calls correct manually. Secondly, an independent program like lint will probably always be more scrupulous at enforcing compatible, portable coding practices than will a particular, implementation-specific, feature- and extension-laden compiler. (Some vendors seem to introduce incompatible extensions deliberately, perhaps to lock in market share.) Section 8. Memory Allocation 43. Why doesn't this program work? main() { char *answer; printf("Type something:\n"); gets(answer); printf("You typed \"%s\"\n", answer); } A: The pointer variable "answer," which is handed to the gets function as the location into which the response should be stored, has not been set to point to any valid storage. It is an uninitialized variable, just as is the variable i in this example: main() { int i; printf("i = %d\n", i); } That is, we cannot say where the pointer "answer" points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that "answer" starts out as a null pointer.) The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation: #include <stdio.h> #include <string.h> main() { char answer[100], *p; printf("Type something:\n"); fgets(answer, 100, stdin); if((p = strchr(answer, '\n')) != NULL) *p = '\0'; printf("You typed \"%s\"\n", answer); } Note that this example also uses fgets instead of gets (always a good idea), so that the size of the array can be specified, so that fgets will not overwrite the end of the array if the user types an overly-long line. (Unfortunately, fgets does not automatically delete the trailing \n, as gets would.) It would also be possible to use malloc to allocate the answer buffer, and/or to parameterize its size (#define ANSWERSIZE 100). 44. I can't get strcat to work. I tried #include <string.h> main() { char *s1 = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); printf("%s\n", s3); } but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. C does not provide a true string type. C programmers use char *'s for strings, but must always keep allocation in mind. The compiler will only allocate memory for objects explicitly mentioned in the source code (in the case of "strings," this includes character arrays and string literals). The programmer must arrange (explicitly) for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or calling malloc. The simple strcat example could be fixed with something like char s1[20] = "Hello, "; char *s2 = "world!"; Note, however, that strcat appends the string pointed to by its second argument to that pointed to by the first, and merely returns its first argument, so the s3 variable is superfluous. Reference: CT&P Sec. 3.2 p. 32. 45. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. The Synopsis section at the top of a Unix-style man page can be misleading. The code fragments presented there are closer to the function definition used by the call's implementor than the invocation used by the caller. In particular, many routines accept pointers (e.g. to strings or structs), and the caller usually passes the address of some object (an array, or an entire struct). Another common example is stat(). 46. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages for malloc stated that the contents of freed memory was "left undisturbed;" this ill-advised guarantee is not universal and is not required by ANSI. Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list: struct list *listp, *nextp; for(listp = base; listp != NULL; listp = nextp) { nextp = listp->next; free((char *)listp); } and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer. References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10 p. 95. 47. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context. alloca cannot be written portably, and is difficult to implement on machines without a stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), 100, stdin). For these reasons, alloca cannot be used in programs which must be widely portable, no matter how useful it might be. Section 9. Structures 48. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: What K&R I said was that the restrictions on struct operations would be lifted in a forthcoming version of the compiler, and in fact struct assignment and passing were fully functional in Ritchie's compiler even as K&R I was being published. Although a few early C compilers lacked struct assignment, all modern compilers support it, and it is part of the ANSI C standard, so there should be no reluctance to use it. References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 . 49. How does struct passing and returning work? A: When structures are passed as arguments to functions, the entire struct is typically pushed on the stack, using as many words as are required. (Pointers to structures are often chosen precisely to avoid this overhead.) Structures are typically returned from functions in a location pointed to by an extra, "hidden" argument to the function. Older compilers often used a special, static location for structure returns, although this made struct-valued functions nonreentrant, which ANSI C disallows. Reference: ANSI Sec. 2.2.3 p. 13. 50. The following program works correctly, but it dumps core after it finishes. Why? struct list { char *item; struct list *next; } /* Here is the main program. */ main(argc, argv) ... A: A missing semicolon causes the compiler to believe that main returns a struct list. (The connection is hard to see because of the intervening comment.) When struct-valued functions are implemented by adding a hidden return pointer, the generated code tries to store a struct with respect to a pointer which was not actually passed (in this case, by the C start-up code). Attempting to store a structure into memory pointed to by the argc or argv value on the stack (where the compiler expected to find the hidden return pointer) causes the core dump. Reference: CT&P Sec. 2.3 pp. 21-2. 51. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. A byte- by-byte comparison could be invalidated by random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison would require unacceptable amounts of repetitive, in-line code for large structures. Either method would not necessarily "do the right thing" with pointer fields: oftentimes, equality should be judged by equality of the things pointed to rather than strict equality of the pointers themselves. If you want to compare two structures, you must write your own function to do so. C++ (among other languages) would let you arrange for the == operator to map to your function. References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Rationale Sec. 3.3.9 p. 47. 52. I came across some code that declared a structure like this: struct name { int namelen; char name[1]; }; and then did some tricky allocation to make the name array act like it had several elements. Is this legal and/or portable? A: This trick is popular, although Dennis Ritchie has called it "unwarranted chumminess with the compiler." The ANSI C standard allows it only implicitly. It seems to be portable to all known implementations. (Debugging, array-bounds-checking compilers might issue warnings.) 53. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. If you don't have it, a suggested implementation is #define offsetof(type, mem) ((size_t) \ ((char *)&((type *) 0)->mem - (char *)((type *) 0))) This implementation is not 100% portable; some compilers may legitimately refuse to accept it. See the next question for a usage hint. Reference: ANSI Sec. 4.1.5 . 54. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is offsetb = offsetof(struct a, b) If structp is a pointer to an instance of this structure, and b is an int field with offset as computed above, b's value can be set indirectly with *(int *)((char *)structp + offsetb) = value; Section 10. Declarations 55. I can't seem to define a linked list node which contains a pointer to itself. I tried typedef struct { char *item; NODEPTR next; } NODE, *NODEPTR; but the compiler gave me error messages. Can't a struct in C contain a pointer to itself? A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. The problem is that the example above attempts to hide the struct pointer behind a typedef, which is not complete at the time it is used. First, rewrite it without a typedef: struct node { char *item; struct node *next; }; Then, if you wish to use typedefs, define them after the fact: typedef struct node NODE, *NODEPTR; Alternatively, define the typedefs first (using the line just above) and follow it with the full definition of struct node, which can then use the NODEPTR typedef for the "next" field. References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 . 56. How can I define a pair of mutually referential structures? I tried typedef struct { int structafield; STRUCTB *bpointer; } STRUCTA; typedef struct { int structbfield; STRUCTA *apointer; } STRUCTB; but the compiler doesn't know about STRUCTB when it is used in struct a. A: Again, the problem is not the pointers but the typedefs. First, define the two structures without using typedefs: struct a { int structafield; struct b *bpointer; }; struct b { int structbfield; struct a *apointer; }; The compiler can accept the field declaration struct b *bpointer within struct a, even though it has not yet heard of struct b. Occasionally it is necessary to precede this couplet with the empty declaration struct b; to mask the declarations (if in an inner scope) from a different struct b in an outer scope. Again, the typedefs could also be defined before, and then used within, the definitions for struct a and struct b. Problems arise only when an attempt is made to define and use a typedef within the same declaration. References: H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 . 57. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: This question can be answered in at least three ways (all assume the hypothetical array is to have 5 elements): 1. char *(*(*a[5])())(); 2. Build it up in stages, using typedefs: typedef char *cp; /* pointer to char */ typedef cp fpc(); /* function returning pointer to char */ typedef fpc *pfpc; /* pointer to above */ typedef pfpc fpfpc(); /* function returning... */ typedef fpfpc *pfpfpc; /* pointer to... */ pfpfpc a[5]; /* array of... */ 3. Use the cdecl program, which turns English into C and vice versa: $ cdecl cdecl> declare a as array 5 of pointer to function returning pointer to function returning pointer to char char *(*(*a[5])())() cdecl> cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions). Any good book on C should explain techniques for reading these complicated C declarations "inside out" to understand them ("declaration mimics use"). Reference: H&S Sec. 5.10.1 p. 116. 58. So where can I get cdecl? A: Several public-domain versions are available. One is in volume 14 of comp.sources.unix . (Commercial versions may also be available, at least one of which was shamelessly lifted from the public domain copy submitted by Graham Ross, one of cdecl's originators.) See question 82. Reference: K&R II Sec. 5.12 . 59. I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one? A: Use something like extern int func(); int (*fp)() = func; When the name of a function appears in an expression but is not being called (i.e. is not followed by a "("), it "decays" into a pointer (i.e. its address is implicitly taken), analagously to the implicit decay of an array into a pointer to its first element. An explicit extern declaration for the function is normally needed, since implicit external function declaration does not happen in this case (again, because the function name is not followed by a "("). 60. I've seen different methods used for calling through pointers to functions. What's the story? A: Originally, a pointer to a function had to be "turned into" a "real" function, with the * operator (and an extra pair of parentheses, to keep the precedence straight), before calling: int r, f(), (*fp)() = f; r = (*fp)(); Another analysis holds that functions are always called through pointers, but that "real" functions decay implicitly into pointers (in expressions, as they do in initializations) and so cause no trouble. This reasoning, which was adopted in the ANSI standard, means that r = fp(); is legal and works correctly, whether fp is a function or a pointer to one. (The usage has always been unambiguous; there is nothing you ever could have done with a function pointer followed by an argument list except call through it). An explicit * is harmless, and still allowed (and recommended, if portability to older compilers is important). References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41. Section 11. Boolean Expressions and Variables 61. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. (Using an int for a boolean may be faster, while using char will probably save data space.) The choice between #defines and enums is arbitrary and not terribly interesting. Use any of #define TRUE 1 #define YES 1 #define FALSE 0 #define NO 0 enum bool {false, true}; enum bool {no, yes}; or use raw 1 and 0, as long as you are consistent within one program or project. (The enum may be preferable if your debugger expands enum values when examining variables.) Some people prefer variants like #define TRUE (1==1) #define FALSE (!TRUE) or define "helper" macros such as #define Istrue(e) ((e) != 0) These don't buy anything (see below). 62. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test if((a == b) == TRUE) will work as expected (as long as TRUE is 1), but it is obviously silly. In general, explicit tests against TRUE and FALSE are undesirable, because some library functions (notably isupper, isalpha, etc.) return, on success, a nonzero value which is _not_ necessarily 1. (Besides, if you believe that "if((a == b) == TRUE)" is an improvement over "if(a == b)", why stop there? Why not use "if(((a == b) == TRUE) == TRUE)"?) A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable, or as the return value from a Boolean function, never in a comparison. Preprocessor macros like TRUE and FALSE (and, in fact, NULL) are used for code readability, not because the underlying values might ever change. That "true" is 1 and "false" (and source-code null pointers) 0 is guaranteed by the language. (See also question 8.) References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5 . 63. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. Although many people might have wished otherwise, the ANSI standard says that enumerations may be freely intermixed with integral types, without errors. (If such intermixing were disallowed without explicit casts, judicious use of enums could catch certain programming errors.) The advantages of enums are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enum variables are examined, and that a compiler may generate nonfatal warnings when enums and ints are indiscriminately mixed (such mixing can still be considered bad style even though it is not strictly illegal). References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 . Section 12. Operating System Dependencies 64. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. The delivery of characters from a "keyboard" to a C program is a function of the operating system in use, and cannot be standardized by the C language. If you are using curses, use its cbreak() function. Under UNIX, use ioctl to play with the terminal driver modes (CBREAK or RAW under "classic" versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or Posix systems). Under MS-DOS, use getch(). Under other operating systems, you're on your own. Beware that some operating systems make this sort of thing impossible, because character collection into input lines is done by peripheral processors not under direct control of the CPU running your program. Operating system specific questions are not appropriate for comp.lang.c . Many common questions are answered in frequently- asked questions postings in such groups as comp.unix.questions and comp.os.msdos.programmer . Note that the answers are often not unique even across different variants of Unix. Bear in mind when answering system-specific questions that the answer that applies to your system may not apply to everyone else's. References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1. 65. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. Some versions of curses have a nodelay() function. Depending on your system, you may also be able to use "nonblocking I/O", or a system call named "select", or the FIONREAD ioctl, or kbhit(), or rdchk(), or the O_NDELAY option to open() or fcntl(). 66. How can my program discover the complete pathname to the executable file from which it was invoked? A: Depending on the operating system, argv[0] may contain all or part of the pathname. (It may also contain nothing.) You may be able to duplicate the command language interpreter's search path logic to locate the executable if the name in argv[0] is incomplete. However, there is no guaranteed or portable solution. 67. How can a process change an environment variable in its caller? A: In general, it cannot. Different operating systems implement name/value functionality similar to the Unix environment in many different ways. Whether the "environment" can be usefully altered by a running program, and if so, how, is entirely system-dependent. Under Unix, a process can modify its own environment (some systems provide setenv() or putenv() functions to do this), and the modified environment is passed on to any child processes, but it is _not_ propagated back to the parent process. (The environment of the parent process can only be altered if the parent is explicitly set up to listen for some kind of change requests. The conventional execution of the BSD "tset" program in .profile and .login files effects such a scheme.) 68. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and several others supply chsize(), but there is no truly portable solution. Section 13. Stdio 69. Why does errno contain ENOTTY after a call to printf? A: Many implementations of the stdio package adjust their behavior slightly if stdout is a terminal. To make the determination, these implementations perform an operation which fails (with ENOTTY) if stdout is not a terminal. Although the output operation goes on to complete successfully, errno still contains ENOTTY. This behavior can be mildly confusing, but it is not strictly incorrect, because it is only meaningful for a program to inspect the contents of errno after an error has occurred (that is, after a library function that sets errno on error has returned an error code). Reference: CT&P Sec. 5.4 p. 73. 70. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. Several mechanisms attempt to perform the fflush for you, at the "right time," but they do not always work, particularly when stdout is a pipe rather than a terminal. 71. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. In particular, "\n" in a format string does not mean "expect a newline", it means "discard all whitespace". But the only way to discard all whitespace is to continue reading the stream until a non-whitespace character is seen (which is then left in the buffer for the next input), so the effect is that it keeps going until it sees a nonblank line. 72. So what should I use instead? A: You could use a "%c" format, which will read one character that you can then manually compare against a newline; or "%*c" and no variable if you're willing to trust the user to hit a newline; or "%*[^\n]%*c" to discard everything up to and including the newline. Usually the best solution is to use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. 73. How can I recover the file name given an open file descriptor? A: This problem is, in general, insoluble. Under Unix, for instance, a scan of the entire disk, (perhaps requiring special permissions) would be required, and would fail if the file descriptor were a pipe (and could give a misleading answer for a file with multiple links). It is best to remember the names of open files yourself (perhaps with a wrapper function around fopen). Section 14. Style 74. Here's a neat trick: if(!strcmp(s1, s2)) Is this good style? A: No. This is a classic example of C minimalism carried to an obnoxious degree. The test succeeds if the two strings are equal, but its form strongly suggests that it tests for inequality. A much better solution is to use a macro: #define Streq(s1, s2) (strcmp(s1, s2) == 0) 75. What's the best style for code layout in C? A: K&R, while providing the example most often copied, also supply a good excuse for avoiding it: The position of braces is less important; we have chosen one of several popular styles. Pick a style that suits you, then use it consistently. It is more important that the layout chosen be consistent (with itself, and with nearby or common code) than that it be "perfect." If your coding environment (i.e. local custom or company policy) does not suggest a style, and you don't feel like inventing your own, just copy K&R. (The tradeoffs between various indenting and brace placement options can be exhaustively and minutely examined, but don't warrant repetition here. See also the Indian Hill Style Guide.) Reference: K&R I Sec. 1.2 p. 10. 76. Where can I get the "Indian Hill Style Guide" and other coding standards? A: Various documents are available for anonymous ftp from: Site: File or directory: cs.washington.edu ~ftp/pub/cstyle.tar.Z (128.95.1.4) (the updated Indian Hill guide) cs.toronto.edu doc/programming giza.cis.ohio-state.edu pub/style-guide prep.ai.mit.edu pub/gnu/standards.text Section 15. Miscellaneous 77. Can someone tell me how to write itoa (the inverse of atoi)? A: Just use sprintf. (You'll have to allocate space for the result somewhere anyway; see questions 43 and 44. Don't worry that sprintf may be overkill, potentially wasting run time or code space; it works well in practice.) 78. I know that the library routine localtime will convert a time_t into a broken-down struct tm, and that ctime will convert a time_t to a printable string. How can I perform the inverse operations of converting a struct tm or a string into a time_t? A: ANSI C specifies a library routine, mktime, which converts a struct tm to a time_t. Several public-domain versions of this routine are available in case your compiler does not support it yet. Converting a string to a time_t is harder, because of the wide variety of date and time formats which should be parsed. Public- domain routines have been written for performing this function, as well, but they are less likely to become standardized. References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI Sec. 4.12.2.3 . 79. How can I write data files which can be read on other machines with different word size, byte order, or floating point formats? A: The best solution is to use a text file (usually ASCII), written with fprintf and read with fscanf or the like. (Similar advice also applies to network protocols.) Be very skeptical of arguments which imply that text files are too big, or that reading and writing them is too slow. Not only is their efficiency frequently acceptable in practice, but the advantages of being able to manipulate them with standard tools can be overwhelming. If the binary format is being imposed on you by an existing program, first see if you can get that program changed to use a more portable format. If you must use a binary format, you can improve portability, and perhaps take advantage of prewritten I/O libraries, by making use of standardized formats such as Sun's XDR, OSI's ASN.1, or CCITT's X.409 . 80. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: Standard headers exist in part so that definitions appropriate to your compiler, operating system, and processor can be supplied. You cannot just pick up a copy of someone else's header file and expect it to work, unless that person is using exactly the same environment. Ask your compiler vendor why the file was not provided (or to send a replacement copy). 81. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available: p2c written by Dave Gillespie, and posted to comp.sources.unix in March, 1990 (Volume 21). ptoc another comp.sources.unix contribution, this one written in Pascal (comp.sources.unix, Volume 10, also patches in Volume 13?). f2c jointly developed by people from Bell Labs, Bellcore, and Carnegie Mellon. To find about f2c, send the mail message "send index from f2c" to netlib@research.att.com or research!netlib. (It is also available via anonymous ftp on research.att.com, in directory dist/f2c.) FOR_C Available from: Cobalt Blue 2940 Union Ave., Suite C San Jose, CA 95124 (408) 723-0474 Promula.Fortran Available from Promula Development Corp. 3620 N. High St., Suite 301 Columbus, OH 43214 (614) 263-5454 The comp.sources.unix archives also contain converters between "K&R" C and ANSI C. 82. Where can I get copies of all these public-domain programs? A: If you have access to Usenet, see the regular postings in the comp.sources.unix and comp.sources.misc newsgroups, which describe, in some detail, the archiving policies and how to retrieve copies. The usual approach is to use anonymous ftp and/or uucp from a central, public-spirited site, such as uunet.uu.net. However, this article cannot track or list all of the available archive sites and how to access them. The comp.archives newsgroup contains numerous announcements of anonymous ftp availability of various items. 83. Where can I get the winners of the old Obfuscated C Contests? When will the next contest be held? A: Send mail to {pacbell,uunet,utzoo}!hoptoad!obfuscate . The contest is usually announced in March, with entries due in May. Contest announcements are posted in several obvious places. The winning entries are archived on uunet (see question 82). 84. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? (And vice versa?) A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use, and may not be possible at all. Read your compiler documentation very carefully; sometimes there is a "mixed-language programming guide," although the techniques for passing arguments and ensuring correct run-time startup are often arcane. 85. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good, mostly because of the possibility of accidentally leaving comments unclosed by including the characters "/*" within them. For this reason, it is usually better to "comment out" large sections of code, which might contain comments, with #ifdef or #if 0. The character sequences /* and */ are not special within double- quoted strings, and do not therefore introduce comments, because a program (particularly one which is generating C code as output) might want to print them. It is hard to imagine why anyone would want or need to place a comment inside a quoted string. It is easy to imagine a program needing to print "/*". Reference: ANSI Rationale Sec. 3.1.9 p. 33. 86. My floating-point calculations are acting strangely and giving me different answers on different machines. A: Most digital computers use floating-point formats which provide a close but by no means exact simulation of real number arithmetic. Among other things, the associative and distributive laws do not hold completely (i.e. order of operation may be important, repeated addition is not necessarily equivalent to multiplication, and underflow or cumulative precision loss is often a problem). Don't assume that floating-point results will be exact, and especially don't assume that floating-point values can be compared for equality. (Don't throw haphazard "fuzz factors" in, either.) These problems are no worse for C than they are for any other computer language. Floating-point semantics are usually defined as "however the processor does them;" otherwise a compiler for a machine without the "right" model would have to do prohibitively expensive emulations. This article cannot begin to list the pitfalls associated with, and workarounds appropriate for, floating-point work. A good programming text should cover the basics. (Beware, though, that subtle problems can occupy numerical analysts for years.) References: K&P Sec. 6 pp. 115-8. 87. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C (and Ritchie's original PDP-11 compiler), leave out floating point support if it looks like it will not be needed. In particular, the non-floating- point versions of printf and scanf save space by not including code to handle %e, %f, and %g. It happens that Turbo C's heuristics for determining whether the program uses floating point are occasionally insufficient, and the programmer must insert one dummy explicit floating-point operation to force loading of floating-point support. Unfortunately, an apparently common sort of program (thus the frequency of the question) uses scanf to read, and/or printf to print, floating-point values upon which no arithmetic is done. In general, questions about a particular compiler are inappropriate for comp.lang.c . Problems with PC compilers, for instance, will find a more receptive audience in a PC newsgroup (e.g. comp.os.msdos.programmer). 88. Does anyone have a C compiler test suite I can use? A: Plum Hall (1 Spruce Ave., Cardiff, NJ 08232, USA), among others, sells one. 89. Where can I get a YACC grammar for C? A: The definitive grammar is of course the one in the ANSI standard. Several copies are floating around; keep your eyes open. There is one on uunet.uu.net (192.48.96.2) in net.sources/ansi.c.grammar.Z . FSF's GNU C compiler contains a grammar, as does the appendix to K&R II. References: ANSI Sec. A.2 . 90. How do you pronounce "char"? What's that funny name for the "#" character? A: You can pronounce the C keyword "char" like the English words "char," "care," or "car;" the choice is arbitrary. Bell Labs once proposed the (now obsolete) term "octothorpe" for the "#" character. Trivia questions like these aren't any more pertinent for comp.lang.c than they are for any of the other groups they frequently come up in. The "jargon file" (also published as _The Hacker's Dictionary_) contains lots of tidbits like these, as does the official Usenet ASCII pronunciation list, maintained by Maarten Litmaath. (The pronunciation list also appears in the jargon file under ASCII, as well as in the comp.unix frequently-asked questions list.) 91. Where can I get extra copies of this list? What about back issues? A: For now, just pull it off the net; it is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Eventually, it may be available for anonymous ftp, or via a mailserver. (Note that the size of the list is monotonically increasing; older copies are obsolete and don't contain much, except the occasional typo, that the current list doesn't.) Bibliography ANSI American National Standard for Information Systems -- Programming Language -- C, ANSI X3.159-1989. H&S Samuel P. Harbison and Guy L. Steele, C: A Reference Manual, Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0. (A third edition has recently been released.) PCS Mark R. Horton, Portable C Software, Prentice Hall, 1990, ISBN 0-13-868050-7. K&P Brian W. Kernighan and P.J. Plaugher, The Elements of Programming Style, Second Edition, McGraw-Hill, 1978, ISBN 0- 07-034207-5. K&R I Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall, 1978, ISBN 0-13-110163-3. K&R II Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Second Edition, Prentice Hall, 1988, ISBN 0-13- 110362-8, 0-13-110370-9. CT&P Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989, ISBN 0-201-17928-8. There is a more extensive bibliography in the revised Indian Hill style guide (see question 76). Acknowledgements Thanks to Sudheer Apte, Mark Brader, Joe Buehler, Raymond Chen, Christopher Calabrese, James Davies, Norm Diamond, Ray Dunn, Stephen M. Dunn, Bjorn Engsig, Doug Gwyn, Tony Hansen, Joe Harrington, Guy Harris, Karl Heuer, Blair Houghton, Kirk Johnson, Andrew Koenig, John Lauro, Christopher Lott, Tim McDaniel, Evan Manning, Mark Moraes, Francois Pinard, randall@virginia, Rich Salz, Chip Salzenberg, Paul Sand, Doug Schmidt, Patricia Shanahan, Joshua Simons, Henry Spencer, Erik Talvola, Clarke Thatcher, Chris Torek, Ed Vielmetti, and Freek Wiedijk, who have contributed, directly or indirectly, to this article. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained. The C code in this article (vstrcat, error, etc.) is public domain and may be used without restriction.
scs@adam.mit.edu (Steve Summit) (02/14/91)
[Last modified February 5, 1991 by scs.] This article contains minimal answers to the comp.lang.c frequently- asked questions list. Please see the long version (posted on the first of each month) for more detailed explanations and references. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic function calls) a constant 0 with an appropriate explicit cast is required. 3. But aren't pointers the same as ints? A: Not since the early days. 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0), which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. I use the preprocessor macro "#define Nullptr(type) (type *)0 " to help me build null pointers of the correct type. A: This trick does not buy much. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 9. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler was broken. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" (written in lower case in this article) is a language concept whose particular internal value does not matter. A "null pointer" is requested in source code with the character "0". "NULL" (always in capital letters) is a preprocessor macro, which is always #defined as 0 (or (void *)0). 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. 14. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." Section 2. Arrays and Pointers 15. I had the declaration char a[5] in one source file, and in another I declared extern char *a. Why didn't it work? A: The declaration extern char *a simply does not match the actual definition. Use extern char a[]. 16. But I heard that char a[] was identical to char *a. A: This identity (that a pointer declaration is interchangeable with an array declaration, usually unsized) holds _only_ for formal parameters to functions. Otherwise, the two forms are not interchangeable. 17. So what is meant by the "equivalence of pointers and arrays" in C? A: Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the fact that arrays decay into pointers within expressions, and that pointers and arrays can both be dereferenced using array-like subscript notation. 18. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? A: Yes, array subscripting is commutative in C. The array subscripting operation a[e] is defined as being equivalent to *((a)+(e)). 19. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 20. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. 21. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Section 3. Order of Evaluation 22. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++); " prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 23. But what about the &&, ||, and comma operators? A: There is a special exception for those operators, (as well as ?: ); left-to-right evaluation is guaranteed. Section 4. ANSI C 24. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. The Standard has also been adopted as ISO/IEC 9899:1990. 25. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for addresses. 26. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: There are several such programs, many in the public domain. 27. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed by using either new-style (prototype) or old-style syntax consistently. 28. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which cannot be forced (by mere words in a Standard) to upgrade. Section 5. C Preprocessor 29. How can I write a macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 30. I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b ", but it doesn't work any more. A: Try the ANSI token-pasting operator ##. 31. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (i.e. no single apostrophes), and no newlines inside quotes. 32. What's the best way to write a multi-statement cpp macro? A: #define Func() do {stmt1; stmt2; ... } while(0) /* (no trailing ;) */ 33. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Section 6. Variable-Length Argument Lists 34. How can I write a function that takes a variable number of arguments? A: Use varargs or stdarg. 35. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 36. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 37. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 38. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Section 7. Lint 39. I just typed in this program, and it's acting strangely. Can you see anything wrong with it? A: Try running lint first. 40. How can I shut off the "warning: possible pointer alignment problem" message lint gives me for each call to malloc? A: It may be easier simply to ignore the message, perhaps in an automated way with grep -v. 41. Where can I get an ANSI-compatible lint? A: See the unabridged list for two commercial products. 42. Don't ANSI function prototypes render lint obsolete? A: No. A good compiler may match most of lint's diagnostics; few provide all. Section 8. Memory Allocation 43. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 44. I can't get strcat to work. I tried "char *s1 = "Hello, ", *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. 45. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. 46. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 47. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. Section 9. Structures 48. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 49. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 50. I have a program which works correctly, but dumps core after it finishes. Why? A: Check to see if a structure type declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. 51. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 52. I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make the array act like it had several elements. Is this legal and/or portable? A: The ANSI C standard allows it only implicitly. 53. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 54. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Section 10. Declarations 55. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 56. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. 57. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: char *(*(*a[5])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 58. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. 59. How do I initialize a pointer to a function? A: Use something like "extern int func(); int (*fp)() = func; " . 60. I've seen different methods used for calling through pointers to functions. A: The extra parentheses and explicit * are now officially optional, although some older implementations require them. Section 11. Boolean Expressions and Variables 61. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 62. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 63. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enumerations are compatible with integral types. Section 12. Operating System Dependencies 64. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 65. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 66. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 67. How can a process change an environment variable in its caller? A: In general, it cannot. 68. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and several others supply chsize(), but there is no truly portable solution. Section 13. Stdio 69. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 70. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) at any point within your program at which output should definitely be visible. 71. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 72. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. 73. How can I recover the file name given an open file descriptor? A: This problem is, in general, insoluble. It is best to remember the names of open files yourself. Section 14. Style 74. Is the code "if(!strcmp(s1, s2))" good style? A: No. 75. What's the best style for code layout in C? A: There is no one "best style," but see the full list for a few suggestions. 76. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. Section 15. Miscellaneous 77. Can someone tell me how to write itoa? A: Just use sprintf. 78. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 79. How can I write data files which can be read on other machines with different data formats? A: The best solution is to use a text file. 80. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 81. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 82. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups for information. 83. Where can I get the winners of the old Obfuscated C Contests? When will the next contest be held? A: Send mail to {pacbell,uunet,utzoo}!hoptoad!obfuscate . 84. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 85. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 86. My floating-point calculations are acting strangely and giving me different answers on different machines. A: See the full list for a brief explanation, or any good programming book for a better one. 87. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 88. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 89. Where can I get a YACC grammar for C? A: See the unabridged list. 90. How do you pronounce "char"? What's that funny name for the "#" character? A: Like the English words "char," "care," or "car" (your choice); "octothorpe." 91. Where can I get extra copies of this list? A: For now, just pull it off the net; the unabridged version is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990, 1991 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (03/01/91)
[Last modified February 28, 1991 by scs.] Certain topics come up again and again on this newsgroup. They are good questions, and the answers may not be immediately obvious, but each time they recur, much net bandwidth and reader time is wasted on repetitive responses, and on tedious corrections to the incorrect answers which are inevitably posted. This article, which is posted monthly, attempts to answer these common questions definitively and succinctly, so that net discussion can move on to more constructive topics without continual regression to first principles. This article does not, and cannot, provide an exhaustive discussion of every subtle point and counterargument which could be mentioned with respect to these topics. Cross-references to standard C publications have been provided, for further study by the interested and dedicated reader. No mere newsgroup article can substitute for thoughtful perusal of a full-length language reference manual. Anyone interested enough in C to be following this newsgroup should also be interested enough to read and study one or more such manuals, preferably several times. Some vendors' compiler manuals are unfortunately inadequate; a few even perpetuate some of the myths which this article attempts to refute. Several noteworthy books on C are listed in this article's bibliography. If you have a question about C which is not answered in this article, please try to answer it by checking a few of the referenced books, or by asking knowledgeable colleagues, before posing your question to the net at large. There are many people on the net who are happy to answer questions, but the volume of repetitive answers posted to one question, as well as the growing numbers of questions as the net attracts more readers, can become oppressive. If you have questions or comments prompted by this article, please reply by mail rather than following up -- this article is meant to decrease net traffic, not increase it. Besides listing frequently-asked questions, this article also summarizes frequently-posted answers. Even if you know all the answers, it's worth skimming through this list once in a while, so that when you see one of its questions unwittingly posted, you won't have to waste time answering. This article is always being improved. Your input is welcomed. Send your comments to scs@adam.mit.edu, scs%adam.mit.edu@mit.edu, and/or mit-eddie!adam!scs; this article's From: line may be unusable. The questions answered here are divided into several categories: 1. Null Pointers 2. Arrays and Pointers 3. Order of Evaluation 4. ANSI C 5. C Preprocessor 6. Variable-Length Argument Lists 7. Lint 8. Memory Allocation 9. Structures 10. Declarations 11. Boolean Expressions and Variables 12. Operating System Dependencies 13. Stdio 14. Style 15. Miscellaneous (Fortran to C converters, etc.) Herewith, some frequently-asked questions and their answers: Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: The language definition states that for each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. That is, the address-of operator & will never yield a null pointer, nor will a successful call to malloc. (malloc returns a null pointer when it fails, and this is a typical use of null pointers: as a "special" pointer value with some other meaning, usually "not allocated" or "not pointing anywhere yet.") A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere (that is, at some random object, or at a garbage or unallocated address). See also questions 51, 57, and 89. As mentioned in the definition above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different. Although programmers need not know the internal values, the compiler must always be informed which type of null pointer is required, so it can make the distinction if necessary (see below). References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38. 2. How do I "get" a null pointer in my programs? A: According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal: char *p = 0; if(p != 0) However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. For instance, the Unix system call "execl" takes a variable-length, null- pointer-terminated list of character pointer arguments. To generate a null pointer in a function call context, an explicit cast is typically required: execl("/bin/sh", "sh", "-c", "ls", (char *)0); If the (char *) cast were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong.) When function prototypes are in scope, argument passing becomes an "assignment context," and casts may safely be omitted, since the prototype tells the compiler that a pointer is required, and of which type, enabling it to correctly cast unadorned 0's. Function prototypes cannot provide the types for variable arguments in variable-length argument lists, however, so explicit casts are still required for those arguments. It is safest always to cast null pointer function arguments, to guard against varargs functions or those without prototypes, to allow interim use of non-ANSI compilers, and to demonstrate that you know what you are doing. Summary: Unadorned 0 okay: Explicit cast required: initialization function call, no prototype in scope assignments variable argument to comparisons varargs function function call, prototype in scope, fixed argument References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI Sec. 3.2.2.3 . 3. But aren't pointers the same as ints? A: Not since the early days. Attempting to turn pointers into integers, or to build pointers out of integers, has always been machine-dependent and unportable, and doing so is strongly discouraged. (Any object pointer may be cast to the "universal" pointer type void *, or char * under a pre-ANSI compiler, when heterogeneous pointers must be passed around.) It is no longer guaranteed that a pointer can be cast to a "suitably capacious" integer and back, unchanged. References: K&R I Sec. 5.6 pp. 102-3; ANSI Sec. 3.2.2.3 p. 37, Sec. 3.3.4 pp. 46-7. 4. What is NULL and how is it #defined? A: As a matter of style, many people prefer not to have unadorned 0's scattered throughout their programs. For this reason, the preprocessor macro NULL is #defined (by <stdio.h> or <stddef.h>), with value 0 (or (void *)0, about which more later). A programmer who wishes to make explicit the distinction between 0 the integer and 0 the null pointer can then use NULL whenever a null pointer is required. This is a stylistic convention only; the preprocessor turns NULL back to 0 which is then recognized by the compiler (in pointer contexts) as before. In particular, a cast may still be necessary before NULL (as before 0) in a function call argument. (The table under question 2 above applies for NULL as well as 0.) NULL should _only_ be used for pointers; see question 9. References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38, Rationale Sec. 4.1.5 p. 74. 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: Programmers should never need to know the internal representation(s) of null pointers, because they are normally taken care of by the compiler. If a machine uses a nonzero bit pattern for null pointers, it is the compiler's responsibility to generate it when the programmer requests, by writing "0" or "NULL," a null pointer. Therefore, #defining NULL as 0 on a machine for which internal null pointers are nonzero is as valid as on any other, because the compiler must (and can) still generate the machine's correct null pointers in response to unadorned 0's seen in pointer contexts. 6. If NULL were defined as follows: #define NULL (char *)0 wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. The suggested #definition would make uncast NULL arguments to functions expecting pointers to characters to work correctly, but pointer arguments to other types would still be problematical, and legal constructions such as FILE *fp = NULL; could fail. Nevertheless, ANSI C allows the alternate #define NULL (void *)0 definition for NULL. Besides helping incorrect programs to work (but only on machines with all pointers the same, thus questionably valid assistance) this definition may catch programs which use NULL incorrectly (e.g. when the ASCII NUL character was really intended). 7. I use the preprocessor macro #define Nullptr(type) (type *)0 to help me build null pointers of the correct type. A: This trick, though popular in some circles, does not buy much. It is not needed in assignments and comparisons; see question 2. It does not even save keystrokes. Its use suggests to the reader that the author is shaky on the subject of null pointers, and requires the reader to check the #definition of the macro, its invocations, and _all_ other pointer usages much more carefully. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: When C requires the boolean value of an expression (in the if, while, for, and do statements, and with the &&, ||, !, and ?: operators), a false value is produced when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes if(expr) where "expr" is any expression at all, the compiler essentially acts as if it had been written as if(expr != 0) Substituting the trivial pointer expression "p" for "expr," we have if(p) is equivalent to if(p != 0) and this is a comparison context, so the compiler can tell that the (implicit) 0 is a null pointer, and use the correct value. There is no trickery involved here; compilers do work this way, and generate identical code for both statements. The internal representation of a pointer does _not_ matter. The boolean negation operator, !, can be described as follows: !expr is essentially equivalent to expr?0:1 It is left as an exercise for the reader to show that if(!p) is equivalent to if(p == 0) "Abbreviations" such as if(p), though perfectly legal, are considered by some to be bad style. See also question 74. References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and 3.6.5 . 9. If "NULL" and "0" are equivalent, which should I use? A: Many programmers believe that "NULL" should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding "NULL" and "0" is only compounded by hiding "0" behind a #definition, and prefer to use unadorned "0" instead. There is no one right answer. C programmers must understand that "NULL" and "0" are interchangeable and that an uncast "0" is perfectly acceptable in initialization, assignment, and comparison contexts. Any usage of "NULL" (as opposed to "0") should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's. NULL should _not_ be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (ANSI allows the #definition of NULL to be (void *)0, which will not work in non-pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition #define NUL '\0' if you must. Reference: K&R II Sec. 5.4 p. 102. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. Although preprocessor macros are often used in place of numbers because the numbers might change, this is _not_ the reason that NULL is used in place of 0. Once again, the language guarantees that source-code 0's (in pointer contexts) generate null pointers. NULL is used only as a stylistic convention. 11. I once used a compiler that wouldn't work unless NULL was used. A: Unless the code being compiled was nonportable (see question 6), that compiler was probably broken. In general, making decisions about a language based on the behavior of one particular compiler is likely to be counterproductive. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: When the term "null" or "NULL" is casually used, one of several things may be meant: 1. The conceptual null pointer, the abstract language concept defined in question 1. It is implemented with... 2. The internal (or run-time) representation of a null pointer, which may or may not be all-bits-0 and which may be different for different pointer types. The actual values should be of concern only to compiler writers. Authors of C programs never see them, since they use... 3. The source code syntax for null pointers, which is the single character "0". It is often hidden behind... 4. The NULL macro, which is #defined to be "0" or "(void *)0". Finally, as a red herring, we have... 5. The ASCII null character (NUL), which does have all bits zero, but has no relation to the null pointer except in name. This article always uses the phrase "null pointer" (in lower case) for sense 1, the character "0" for sense 3, and the capitalized word "NULL" for sense 4. 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: C programmers traditionally like to know more than they need to about the underlying machine implementation. The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. The construct "if(p == 0)" is easily misread as calling for conversion of p to an integral type, rather than 0 to a pointer type, before the comparison. Finally, the distinction between the several uses of the term "null" (listed above) is often overlooked. One good way to wade out of the confusion is to imagine that C had a keyword (perhaps "nil", like Pascal) with which null pointers were requested. The compiler could either turn "nil" into the correct type of null pointer, when it could determine the type from the source code (as it does with 0's in reality), or complain when it could not. Now, in fact, in C the keyword for a null pointer is not "nil" but "0", which works almost as well, except that an uncast "0" in a non-pointer context generates an integer zero instead of an error message, and if that uncast 0 was supposed to be a null pointer, the code may not work. 14. I'm still confused. I just can't understand all this null pointer stuff. A: Follow these two simple rules: 1. When you want to refer to a null pointer in source code, use "0" or "NULL". 2. If the usage of "0" or "NULL" is an argument in a function call, cast it to the pointer type expected by the function being called. The rest of the discussion has to do with other people's misunderstandings, or with the internal representation of null pointers, which you shouldn't need to know. Understand questions 1, 2, and 4, and consider 9 and 13, and you'll do fine. 15. Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? A: If for no other reason, doing so would be ill-advised because it would unnecessarily constrain implementations which would otherwise naturally represent null pointers by special, nonzero bit patterns, particularly when those values would trigger automatic hardware traps for invalid accesses. Besides, what would this requirement really accomplish? Proper understanding of null pointers does not require knowledge of the internal representation, whether zero or nonzero. Assuming that null pointers are internally zero does not make any code easier to write (except for a certain ill-advised usage of calloc; see question 57). Known-zero internal pointers would not obviate casts in function calls, because the _size_ of the pointer might still be different from that of an int. (If "nil" were used to request null pointers rather than "0," as mentioned in question 13, the urge to assume an internal zero representation would not even arise.) 16. Seriously, have any actual machines really used nonzero null pointers? A: "Certain Prime computers use a value different from all- bits-0 to encode the null pointer. Also, some large Honeywell-Bull machines use the bit pattern 06000 to encode the null pointer. On such machines, the assignment of 0 to a pointer yields the special bit pattern that designates the null pointer." -- Portable C, by H. Rabinowitz and Chaim Schaap, Prentice-Hall, 1990, page 147. The "certain Prime computers" were the segmented 50 series, which used segment 07777, offset 0 for the null pointer, at least for PL/I. Later models used segment 0, offset 0 for null pointers in C, necessitating new instructions such as TCNP (Test C Null Pointer), evidently as a sop to all the extant poorly-written C code which made incorrect assumptions. The Symbolics Lisp Machine, a tagged architecture, does not even have conventional numeric pointers; it uses the pair <NIL, 0> (basically a nonexistent <object, offset> handle) as a C null pointer. Section 2. Arrays and Pointers 17. I had the definition char x[6] in one source file, and in another I declared extern char *x. Why didn't it work? A: The declaration extern char *x simply does not match the actual definition. The type "pointer-to-type-T" is not the same as "array-of-type-T." Use extern char x[]. References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5. 18. But I heard that char x[] was identical to char *x. A: Not at all. (What you heard has to do with formal parameters to functions; see question 21.) Arrays are not pointers. The declaration "char a[6];" requests that space for six characters be set aside, to be known by the name "a." That is, there is a location named "a" at which six characters can sit. The declaration "char *p;" on the other hand, requests a place which holds a pointer. The pointer is to be known by the name "p," and can point to any char (or contiguous array of chars) anywhere. As usual, a picture is worth a thousand words. The statements char a[] = "hello"; char *p = "world"; char *p2 = a; would result in data structures which could be represented like this: +---+---+---+---+---+---+ a: | h | e | l | l | o |\0 | +---+---+---+---+---+---+ ^ | +--|--+ p2: | * | +-----+ +-----+ +---+---+---+---+---+---+ p: | *======> | w | o | r | l | d |\0 | +-----+ +---+---+---+---+---+---+ 19. You mean that a reference like x[3] generates different code depending on whether x is an array or a pointer? A: Precisely. Referring back to the sample declarations in the previous question, when the compiler sees the expression a[3], it emits code to start at the location "a," move three past it, and fetch the character there. When it sees the expression p[3], it emits code to start at the location "p," fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to. In the example above, both a[3] and p[3] (and p2[3], for that matter) happen to be the character 'l', but that the compiler gets there differently. (See also question 100.) 20. So what is meant by the "equivalence of pointers and arrays" in C? A: Much of the confusion surrounding pointers in C can be traced to a misunderstanding of this statement. Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the following key definition: An identifier of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T. (The exceptions are when the array is the operand of the sizeof() operator or of the & operator, or is a literal string initializer for a character array.) As a consequence of this definition, there is not really any difference in the behavior of the "array subscripting" operator [] as it applies to arrays and pointers. In an expression of the form a[i], the array name "a" decays into a pointer, following the rule above, and is then subscripted exactly as would be a pointer variable in the expression p[i]. In either case, the expression x[i] (where x is an array or a pointer) is, by definition, exactly equivalent to *((x)+(i)). References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec. 5.4.1 p. 93; ANSI Sec. 3.3.2.1, Sec. 3.3.6 . 21. Then why are array and pointer declarations interchangeable as function formal parameters? A: Since arrays decay immediately into pointers, an array is never actually passed to a function. Allowing pointer parameters to be declared as arrays is a simply a way of making it look as though the array was being passed. Some programmers prefer, as a matter of style, to use this syntax to indicate that the pointer parameter is expected to point to the start of an array rather than to some single value. Since functions can never receive arrays as parameters, any parameter declarations which "look like" arrays, e.g. f(a) char a[]; are treated by the compiler as if they were pointers, since that is what the function will receive if an array is passed: f(a) char *a; To repeat, however, this conversion holds only within function formal parameter declarations, nowhere else. If this conversion bothers you, don't use it; many people have concluded that the confusion it causes outweighs the small advantage of having the declaration "look like" the call and/or the uses within the function. References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3 pp. 33-4. 22. Someone explained to me that arrays were really just constant pointers. A: That person did you a disservice. An array name is "constant" in that it cannot be assigned to, but an array is _not_ a pointer, as the discussion and pictures in question 18 should make clear. 23. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? A: Yes, Virginia, array subscripting is commutative in C. This curious fact follows from the pointer definition of array subscripting, namely that a[e] is exactly equivalent to *((a)+(e)), for _any_ expression e and primary expression a, as long as one of them is a pointer expression and one is integral. This unsuspected commutativity is often mentioned in C texts as if it were something to be proud of, but it finds no useful application outside of the Obfuscated C Contest (see also question 97). 24. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays can be confusing, and must be treated carefully. (The confusion is heightened by the existence of incorrect compilers, including some versions of pcc and pcc-derived lint's, which improperly accept assignments of multi-dimensional arrays to multi-level pointers.) If you are passing a two-dimensional array to a function: int array[YSIZE][XSIZE]; f(array); the function's declaration should match: f(int a[][XSIZE]) {...} or f(int (*ap)[XSIZE]) {...} /* ap is a pointer to an array */ In the first declaration, the compiler performs the usual implicit parameter rewriting of "array of array" to "pointer to array;" in the second form the pointer declaration is explicit. Since the called function does not allocate space for the array, it does not need to know the overall size, so the number of "rows," YSIZE, can be omitted. The "shape" of the array is still important, so the "column" dimension XSIZE (and, for 3- or more dimensional arrays, the intervening ones) must be included. If a function is already declared as accepting a pointer to a pointer, it is probably incorrect to pass a two-dimensional array directly to it. 25. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. Arrays of type T decay into pointers to type T, which is convenient; subscripting or incrementing the resultant pointer accesses the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally only useful when operating on multidimensional arrays, if at all. (See question 24 above.) When people speak casually of a pointer to an array, they usually mean a pointer to its first element; the type of this latter pointer is generally more useful. If you really need to declare a pointer to an entire array, use something like "int (*ap)[N];" where N is the size of the array. (See also question 69.) If the size of the array is unknown, N can be omitted, but the resulting type, "pointer to array of unknown size," is almost completely useless. 26. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." The resulting "ragged" array can save space, although it is not necessarily contiguous in memory as a real array would be. Here is a two-dimensional example: int **array = (int **)malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array[i] = (int *)malloc(ncolumns * sizeof(int)); (In "real" code, of course, each return value from malloc should be checked.) You can keep the array's contents contiguous, while making later reallocation of individual rows difficult, with a bit of explicit pointer arithmetic: int **array = (int **)malloc(nrows * sizeof(int *)); array[0] = (int *)malloc(nrows * ncolumns * sizeof(int)); for(i = 1; i < nrows; i++) array[i] = array[0] + i * ncolumns; In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: array[i][j]. If the double indirection implied by the above schemes is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array: int *array = (int *)malloc(nrows * ncolumns * sizeof(int)); However, you must now perform subscript calculations manually, accessing the i,jth element with array[i * ncolumns + j]. (A macro can hide the explicit calculation, but invoking it then requires parentheses and commas which don't look exactly like multidimensional array subscripts.) Section 3. Order of Evaluation 27. Under my compiler, the code int i = 7; printf("%d\n", i++ * i++); prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: Although the postincrement and postdecrement operators ++ and -- perform the operations after yielding the former value, many people misunderstand the implication of "after." It is _not_ guaranteed that the operation is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered "finished" (before the next "sequence point," in ANSI C's terminology). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards. The order of other embedded side effects is similarly undefined. For example, the expression i + (i = 2) does not necessarily yield 4. The behavior of code which contains ambiguous or undefined side effects has always been undefined. (Note, too, that a compiler's choice, especially under ANSI rules, for "undefined behavior" may be to refuse to compile the code.) Don't even try to find out how your compiler implements such things (contrary to the ill-advised exercises in many C textbooks); as K&R wisely point out, "if you don't know _how_ they are done on various machines, that innocence may help to protect you." References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1. (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.) 28. But what about the &&, ||, and comma operators? I see code like "if((c = getchar()) == EOF || c == '\n')" ... A: There is a special exception for those operators, (as well as ?: ); each of them does imply a sequence point (i.e. left-to-right evaluation is guaranteed). Any book on C should make this clear. References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55, CT&P Sec. 3.7 pp. 46-7. Section 4. ANSI C 29. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, including several widespread public reviews, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardizes existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the much-lambasted trigraph sequences). The ANSI C standard also formalizes the C run-time library support routines. The published Standard includes a "Rationale," which explains many of its decisions, and discusses a number of subtle points, including several of those covered here. (The Rationale is "not part of ANSI Standard X3.159-1989, but is included for information only.") The Standard has also been adopted as an international standard, ISO/IEC 9899:1990, although the Rationale is currently not included. 30. How can I get a copy of the ANSI C standard? A: Copies are available from American National Standards Institute 1430 Broadway New York, NY 10018 USA (+1) 212 642 4900 or Global Engineering Documents 2805 McGaw Avenue Irvine, CA 92714 USA (+1) 714 261 1455 (800) 854 7179 (U.S. & Canada) The cost from ANSI is $50.00, plus $6.00 shipping. Quantity discounts are available. (Note that ANSI derives revenues to support its operations from the sale of printed standards, so electronic copies are _not_ available.) The Rationale, by itself, has been printed by Silicon Press, ISBN 0-929306-07-4. 31. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: Two programs, protoize and unprotoize, are being written to convert back and forth between prototyped and "old style" function definitions and declarations. (These programs are _not_ expected to handle full-blown conversion between "Classic" C and ANSI C.) When available, these programs will exist as patches to the FSF GNU C compiler, gcc. Several prototype generators exist, many as modifications to lint. (See also questions 95 and 96.) 32. What's the difference between "char const *p" and "char * const p"? A: "char const *p" is a pointer to a constant character (you can't change the character); "char * const p" is a constant pointer to a (variable) character (i.e. you can't change the pointer). (Read these "inside out" to understand them. See question 69.) 33. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". Old C (and ANSI C, in the absence of prototypes) silently promotes floats to doubles when passing them as arguments, and arranges that doubles being passed are coerced back to floats if the formal parameters are declared that way. The problem can be fixed either by using new-style syntax consistently in the definition: int func(float x) { ... } or by changing the new-style prototype declaration to match the old-style definition: extern int func(double); (In this case, it would be clearest to change the old-style definition to use double as well, as long as the address of that parameter is not taken.) Reference: ANSI Sec. 3.3.2.2 . 34. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (note particularly that an apostrophe within a contracted word could look like the beginning of a character constant), and no newlines inside quotes. Therefore, natural-language comments and pseudocode should always be written between the "official" comment delimiters /* and */. (But see also question 98.) References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37. 35. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which are neither under the control of the ANSI standard nor the C compiler developers on the systems which have them. The limitation is only that identifiers be _significant_ in the first six characters, not that they be restricted to six characters in length. This limitation is annoying, but certainly not unbearable, and is marked in the Standard as "obsolescent," i.e. a future revision will likely relax it. This concession to current, restrictive linkers really had to be made, no matter how vehemently some people oppose it. (The Rationale notes that its retention was "most painful.") If you disagree, or have thought of a trick by which a compiler burdened with a restrictive linker could present the C programmer with the appearance of more significance in external identifiers, read the excellently-worded section 3.1.2 in the X3.159 Rationale (see question 29), which discusses several such schemes and explains why they could not be mandated. References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale Sec. 3.1.2 pp. 19-21. 36. What was noalias and what ever happened to it? A: noalias was another type qualifier, in the same syntactic class as const and volatile, which was intended to assert that the object pointed to was not also pointed to ("aliased") by other pointers. The primary application, which is an important one, would have been for the formal parameters of subroutines designed to perform computations on large arrays. A compiler can not usually take advantage of vectorization or other parallelization hardware (on supercomputers which have it) unless it can ensure that the source and destination arrays do not overlap. The noalias keyword was not backed up by any "prior art," and it was introduced late in the review and approval process. It was phenomenally difficult to define precisely and explain coherently, and sparked widespread, acrimonious debate, including a scathing pan by Dennis Ritchie. It had far-ranging implications, particularly on several standard library interfaces, for which easy fixes were not readily apparent. Because of the criticism and the difficulty of defining noalias well, the Committee wisely declined to adopt it, in spite of its superficial attractions. (When writing a standard, features cannot be introduced halfway; their full integration, and all implications, must be understood.) The need for a mechanism to support parallel implementation of non-overlapping operations remains unfilled (although the C Numerical Extensions Working Group is examining the problem). References: ANSI Sec. 3.9.6 . 37. What are #pragmas and what are they good for? A: The #pragma directive (based on a similar feature in Ada, of all things) provides a single, well-defined "escape hatch" which can be used for all sorts of implementation-specific controls and extensions: source listing control, structure packing, warning suppression (like the old lint /* NOTREACHED */ comments), etc. References: ANSI Sec. 3.8.6 . Section 5. C Preprocessor 38. How can I write a generic macro to swap two values? A: There is no good answer to this question. If the values are integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers, (and the "obvious" supercompressed implementation for integral types a^=b^=a^=b is, strictly speaking, illegal due to multiple side-effects; and it will not work if the two values are the same variable, and...). If the macro is intended to be used on values of arbitrary type (the usual goal), it cannot use a temporary, since it does not know what type of temporary it needs, and standard C does not provide a typeof operator. (GNU C does.) The best all-around solution is probably to forget about using a macro. If you're worried about the use of an ugly temporary, and know that your machine provides an exchange instruction, convince your compiler vendor to recognize the standard three-assignment swap idiom in the optimization phase. 39. I have some old code that tries to construct identifiers with a macro like #define Paste(a, b) a/**/b but it doesn't work any more. A: That comments disappeared entirely and could therefore be used for token pasting was an undocumented feature of some early preprocessor implementations, notably Reiser's. ANSI affirms (as did K&R) that comments are replaced with white space. However, since the need for pasting tokens was demonstrated and real, ANSI introduced a well-defined token-pasting operator, ##, which can be used like this: #define Paste(a, b) a##b Reference: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7. 40. What's the best way to write a multi-statement cpp macro? A: The usual goal is to write a macro that can be invoked as if it were a single function-call statement. This means that the "caller" will be supplying the final semicolon, so the macro body should not. The macro body cannot be a simple brace-delineated compound statement, because syntax errors would result if it were invoked (apparently as a single statement, but with a resultant extra semicolon) as the if branch of an if/else statement with an explicit else clause. The traditional solution is to use #define Func() do { \ /* declarations */ \ stmt1; \ stmt2; \ /* ... */ \ } while(0) /* (no trailing ; ) */ When the "caller" appends a semicolon, this expansion becomes a single statement regardless of context. (An optimizing compiler will remove any "dead" tests or branches on the constant condition 0, although lint may complain.) If all of the statements in the intended macro are simple expressions, with no declarations, conditionals, or loops, another technique is to write a single, parenthesized expression using one or more comma operators. (This technique also allows a value to be "returned.") Reference: CT&P Sec. 6.3 pp. 82-3. 41. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); The obvious disadvantage is that the caller must always remember to use the extra parentheses. (It is often best to use a bona-fide function, which can take a variable number of arguments in a well- defined way, rather than a macro. See questions 42 and 43 below.) Section 6. Variable-Length Argument Lists 42. How can I write a function that takes a variable number of arguments? A: Use the <stdarg.h> header (or, if you must, the older <varargs.h>). Here is a function which concatenates an arbitrary number of strings into malloc'ed memory: #include <stddef.h> /* for NULL, size_t */ #include <stdarg.h> /* for va_ stuff */ #include <string.h> /* for strcat et al */ #include <stdlib.h> /* for malloc */ /* VARARGS1 */ char *vstrcat(char *first, ...) { size_t len = 0; char *retbuf; va_list argp; char *p; if(first == NULL) return NULL; len = strlen(first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) len += strlen(p); va_end(argp); retbuf = malloc(len + 1); /* +1 for trailing \0 */ if(retbuf == NULL) return NULL; /* error */ (void)strcpy(retbuf, first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) (void)strcat(retbuf, p); va_end(argp); return retbuf; } Usage is something like char *str = vstrcat("Hello, ", "world!", (char *)NULL); Note the cast on the last argument. (Also note that the caller must free the returned, malloc'ed storage.) Under a pre-ANSI compiler, rewrite the function definition without a prototype ("char *vstrcat(first) char *first; {"), include <stdio.h> rather than <stddef.h>, replace "#include <stdlib.h>" with "extern char *malloc();", and use int instead of size_t. You may also have to delete the (void) casts, and use the older varargs package instead of stdarg. See the next question for hints. (If you know enough about your machine's architecture, it is possible to pick arguments off of the stack "by hand," but there is little reason to do so, since portable mechanisms exist. If you know how to access arguments "by hand," but have access to neither <stdarg.h> nor <varargs.h>, you could as easily implement <stdarg.h> yourself, leaving your code portable.) References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 . 43. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. Here is an "error" routine which prints an error message, preceded by the string "error: " and terminated with a newline: #include <stdio.h> #include <stdarg.h> /* VARARGS1 */ void error(char *fmt, ...) { va_list argp; fprintf(stderr, "error: "); va_start(argp, fmt); vfprintf(stderr, fmt, argp); va_end(argp); fprintf(stderr, "\n"); } To use the older <varargs.h> package, instead of <stdarg.h>, change the function header to: void error(va_alist) va_dcl { char *fmt; change the va_start line to va_start(argp); and add the line fmt = va_arg(argp, char *); between the calls to va_start and vfprintf. (Note that there is no semicolon after va_dcl.) References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 . 44. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. You're on your own. 45. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Some systems have a nonstandard nargs() function available, but its use is questionable, since it typically returns the number of words pushed, not the number of arguments. (Floating point values and structures are usually passed as several words.) Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. printf-like functions do this by looking for formatting specifiers (%d and the like) in the format string (which is why these functions fail badly if the format string does not match the argument list). Another common technique (useful when the arguments are all of the same type) is to use a sentinel value (often 0, -1, or an appropriately-cast null pointer) at the end of the list (see the execl and vstrcat examples under questions 2 and 42 above). 46. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. You must provide a version of that other function which accepts a va_list pointer, as does vfprintf in the example above. If the arguments must be passed directly as actual arguments (not indirectly through a va_list pointer) to another function which is itself variadic (for which you do not have the option of creating an alternate, va_list-accepting version) no portable solution is possible. (The problem can be solved by resorting to machine-specific assembly language.) Section 7. Lint 47. I just typed in this program, and it's acting strangely. Can you see anything wrong with it? A: Try running lint first. Most C compilers are really only half- compilers, electing not to diagnose numerous source code difficulties which would not actively preclude code generation. That the "other half," better error detection, was deferred to lint, was a fairly deliberate decision on the part of the earliest Unix C compiler authors, but is inexcusable (in the absence of a supplied, consistent lint, or equivalent error checking) in a modern compiler. 48. How can I shut off the "warning: possible pointer alignment problem" message lint gives me for each call to malloc? A: The problem is that traditional versions of lint do not know, and cannot be told, that malloc "returns a pointer to space suitably aligned for storage of any type of object." It is possible to provide a pseudoimplementation of malloc, using a #define inside of #ifdef lint, which effectively shuts this warning off, but a simpleminded #definition will also suppress meaningful messages about truly incorrect invocations. It may be easier simply to ignore the message, perhaps in an automated way with grep -v. 49. Where can I get an ANSI-compatible lint? A: A product called FlexeLint is available (in "shrouded source form," for compilation on 'most any system) from Gimpel Software 3207 Hogarth Lane Collegeville, PA 19426 USA (+1) 215 584 4261 The System V release 4 lint is ANSI-compatible, and is available separately (bundled with other C tools) from Unix Support Labs (a subsidiary of AT&T), or from System V resellers. 50. Don't ANSI function prototypes render lint obsolete? A: Not really. First of all, prototypes work well only if the programmer works assiduously to maintain them, and the effort to do so (plus the extra recompilations required by numerous, more- frequently-modified header files) can rival the toil of keeping function calls correct manually. Secondly, an independent program like lint will probably always be more scrupulous at enforcing compatible, portable coding practices than will any particular, implementation-specific, feature- and extension-laden compiler. (Some vendors seem to introduce incompatible extensions deliberately, perhaps to lock in market share.) Section 8. Memory Allocation 51. Why doesn't this fragment work? char *answer; printf("Type something:\n"); gets(answer); printf("You typed \"%s\"\n", answer); A: The pointer variable "answer," which is handed to the gets function as the location into which the response should be stored, has not been set to point to any valid storage. It is an uninitialized variable, just as is the variable i in int i; printf("i = %d\n", i); That is, we cannot say where the pointer "answer" points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that "answer" starts out as a null pointer. See question 89.) The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation: #include <string.h> char answer[100], *p; printf("Type something:\n"); fgets(answer, 100, stdin); if((p = strchr(answer, '\n')) != NULL) *p = '\0'; printf("You typed \"%s\"\n", answer); Note that this example also uses fgets instead of gets (always a good idea), so that the size of the array can be specified, so that fgets will not overwrite the end of the array if the user types an overly-long line. (Unfortunately, fgets does not automatically delete the trailing \n, as gets would.) It would also be possible to use malloc to allocate the answer buffer, and/or to parameterize its size (#define ANSWERSIZE 100). 52. I can't get strcat to work. I tried char *s1 = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); printf("%s\n", s3); but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. C does not provide an automatically-managed string type. C compilers only allocate memory for objects explicitly mentioned in the source code (in the case of "strings," this includes character arrays and string literals). The programmer must arrange (explicitly) for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or by calling malloc. strcat performs no allocation; the second string is appended to the first one, in place. Therefore, one fix would be to declare the first string as an array with sufficient space: char s1[20] = "Hello, "; Since strcat returns its first argument, the s3 variable is superfluous. Reference: CT&P Sec. 3.2 p. 32. 53. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. The Synopsis section at the top of a Unix-style man page can be misleading. The code fragments presented there are closer to the function definition used by the call's implementor than the invocation used by the caller. In particular, many routines accept pointers (e.g. to structs or strings), and the caller usually passes the address of some object (a struct, or an array -- see questions 20 and 21.) Another common example is stat(). 54. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages for malloc stated that the contents of freed memory was "left undisturbed;" this ill-advised guarantee is not universal and is not required by ANSI. Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list: struct list *listp, *nextp; for(listp = base; listp != NULL; listp = nextp) { nextp = listp->next; free((char *)listp); } and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer. References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10 p. 95. 55. How does free() know how many bytes to free? A: The malloc/free package remembers the size of each block it allocates and returns, so it is not necessary to remind it of the size when freeing. 56. Is it legal to pass a null pointer as the first argument to realloc()? Why would you want to? A: ANSI C sanctions this usage (and the related realloc(..., 0), which frees), but several earlier implementations do not support it, so it is not widely portable. Passing an initially-null pointer to realloc can make it easy to write a self-starting incremental allocation algorithm. References: ANSI Sec. 4.10.3.4 . 57. What is the difference between calloc and malloc? Is it safe to use calloc's zero-fill guarantee for pointer and floating-point values? Does free work on memory allocated with calloc, or do you need a cfree? A: calloc(m, n) is essentially equivalent to p = malloc(m * n); memset(p, 0, m * n); The zero fill is all-bits-zero, and does not therefore guarantee useful zero values for pointers (see questions 1-16) or floating- point values. free can (and should) be used to free the memory allocated by calloc. References: ANSI Secs. 4.10.3 to 4.10.3.2 . 58. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context. alloca cannot be written portably, and is difficult to implement on machines without a stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), 100, stdin). For these reasons, alloca cannot be used in programs which must be widely portable, no matter how useful it might be. Section 9. Structures 59. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: What K&R I said was that the restrictions on struct operations would be lifted in a forthcoming version of the compiler, and in fact struct assignment and passing were fully functional in Ritchie's compiler even as K&R I was being published. Although a few early C compilers lacked struct assignment, all modern compilers support it, and it is part of the ANSI C standard, so there should be no reluctance to use it. References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 . 60. How does struct passing and returning work? A: When structures are passed as arguments to functions, the entire struct is typically pushed on the stack, using as many words as are required. (Pointers to structures are often chosen precisely to avoid this overhead.) Structures are typically returned from functions in a location pointed to by an extra, compiler-supplied "hidden" argument to the function. Older compilers often used a special, static location for structure returns, although this made struct-valued functions nonreentrant, which ANSI C disallows. Reference: ANSI Sec. 2.2.3 p. 13. 61. The following program works correctly, but it dumps core after it finishes. Why? struct list { char *item; struct list *next; } /* Here is the main program. */ main(argc, argv) ... A: A missing semicolon causes the compiler to believe that main returns a struct list. (The connection is hard to see because of the intervening comment.) Since struct-valued functions are usually implemented by adding a hidden return pointer, the generated code for main() actually expects three arguments, although only two were passed (in this case, by the C start-up code). See also question 103. Reference: CT&P Sec. 2.3 pp. 21-2. 62. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. A byte- by-byte comparison could be invalidated by random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison would require unacceptable amounts of repetitive, in-line code for large structures. Either method would not necessarily "do the right thing" with pointer fields: oftentimes, equality should be judged by equality of the things pointed to rather than strict equality of the pointers themselves. If you want to compare two structures, you must write your own function to do so. C++ (among other languages) would let you arrange for the == operator to map to your function. References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Rationale Sec. 3.3.9 p. 47. 63. I came across some code that declared a structure like this: struct name { int namelen; char name[1]; }; and then did some tricky allocation to make the name array act like it had several elements. Is this legal and/or portable? A: This technique is popular, although Dennis Ritchie has called it "unwarranted chumminess with the compiler." The ANSI C standard allows it only implicitly. It seems to be portable to all known implementations. (Compilers which check array bounds carefully might issue warnings.) 64. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available; see <stddef.h>. If you don't have it, a suggested implementation is #define offsetof(type, mem) ((size_t) \ ((char *)&((type *) 0)->mem - (char *)((type *) 0))) This implementation is not 100% portable; some compilers may legitimately refuse to accept it. See the next question for a usage hint. Reference: ANSI Sec. 4.1.5 . 65. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is offsetb = offsetof(struct a, b) If structp is a pointer to an instance of this structure, and b is an int field with offset as computed above, b's value can be set indirectly with *(int *)((char *)structp + offsetb) = value; Section 10. Declarations 66. How do you decide which integer type to use? A: If you might need large values (above 32767 or below -32767), use long. If space is very important (there are large arrays or many structures), use short. Otherwise, use int. If well-defined overflow characteristics are important and/or sign is not, use unsigned. Similar arguments operate when deciding between float and double. Exceptions apply if the address of a variable is taken and must have a particular type. In general, don't try to use char or unsigned char as a "tiny" int type; doing so is often more trouble than it's worth. 67. I can't seem to define a linked list node which contains a pointer to itself. I tried typedef struct { char *item; NODEPTR next; } NODE, *NODEPTR; but the compiler gave me error messages. Can't a struct in C contain a pointer to itself? A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. The problem is that the example above attempts to hide the struct pointer behind a typedef, which is not complete at the time it is used. First, rewrite it without a typedef: struct node { char *item; struct node *next; }; Then, if you wish to use typedefs, define them after the fact: typedef struct node NODE, *NODEPTR; Alternatively, define the typedefs first (using the line just above) and follow it with the full definition of struct node, which can then use the NODEPTR typedef for the "next" field. References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 . 68. How can I define a pair of mutually referential structures? I tried typedef struct { int structafield; STRUCTB *bpointer; } STRUCTA; typedef struct { int structbfield; STRUCTA *apointer; } STRUCTB; but the compiler doesn't know about STRUCTB when it is used in struct a. A: Again, the problem lies not in the pointers but the typedefs. First, define the two structures without using typedefs: struct a { int structafield; struct b *bpointer; }; struct b { int structbfield; struct a *apointer; }; The compiler can accept the field declaration struct b *bpointer within struct a, even though it has not yet heard of struct b. Occasionally it is necessary to precede this couplet with the empty declaration struct b; to mask the declarations (if in an inner scope) from a different struct b in an outer scope. Again, the typedefs could also be defined before, and then used within, the definitions for struct a and struct b. Problems arise only when an attempt is made to define and use a typedef within the same declaration. References: H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 . 69. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: This question can be answered in at least three ways (all assume the hypothetical array is to have 5 elements): 1. char *(*(*a[5])())(); 2. Build it up in stages, using typedefs: typedef char *pc; /* pointer to char */ typedef pc fpc(); /* function returning pointer to char */ typedef fpc *pfpc; /* pointer to above */ typedef pfpc fpfpc(); /* function returning... */ typedef fpfpc *pfpfpc; /* pointer to... */ pfpfpc a[5]; /* array of... */ 3. Use the cdecl program, which turns English into C and vice versa: $ cdecl cdecl> declare a as array 5 of pointer to function returning pointer to function returning pointer to char char *(*(*a[5])())() cdecl> cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions, like the above). Any good book on C should explain how to read these complicated C declarations "inside out" to understand them ("declaration mimics use"). Reference: H&S Sec. 5.10.1 p. 116. 70. So where can I get cdecl? A: Several public-domain versions are available. One is in volume 14 of comp.sources.unix . (Commercial versions may also be available, at least one of which was shamelessly lifted from the public domain copy submitted by Graham Ross, one of cdecl's originators.) See question 96. Reference: K&R II Sec. 5.12 . 71. I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one? A: Use something like extern int func(); int (*fp)() = func; When the name of a function appears in an expression but is not being called (i.e. is not followed by a "("), it "decays" into a pointer (i.e. it has its address implicitly taken), much as an array name does. An explicit extern declaration for the function is normally needed, since implicit external function declaration does not happen in this case (again, because the function name is not followed by a "("). 72. I've seen different methods used for calling through pointers to functions. What's the story? A: Originally, a pointer to a function had to be "turned into" a "real" function, with the * operator (and an extra pair of parentheses, to keep the precedence straight), before calling: int r, f(), (*fp)() = f; r = (*fp)(); Another analysis holds that functions are always called through pointers, but that "real" functions decay implicitly into pointers (in expressions, as they do in initializations) and so cause no trouble. This reasoning, which was adopted in the ANSI standard, means that r = fp(); is legal and works correctly, whether fp is a function or a pointer to one. (The usage has always been unambiguous; there is nothing you ever could have done with a function pointer followed by an argument list except call through it.) An explicit * is harmless, and still allowed (and recommended, if portability to older compilers is important). References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41. Section 11. Boolean Expressions and Variables 73. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. (Using an int for a boolean may be faster, while using char may save data space.) The choice between #defines and enums is arbitrary and not terribly interesting. Use any of #define TRUE 1 #define YES 1 #define FALSE 0 #define NO 0 enum bool {false, true}; enum bool {no, yes}; or use raw 1 and 0, as long as you are consistent within one program or project. (An enum may be preferable if your debugger expands enum values when examining variables.) Some people prefer variants like #define TRUE (1==1) #define FALSE (!TRUE) or define "helper" macros such as #define Istrue(e) ((e) != 0) These don't buy anything (see below). 74. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test if((a == b) == TRUE) will work as expected (as long as TRUE is 1), but it is obviously silly. In general, explicit tests against TRUE and FALSE are undesirable, because some library functions (notably isupper, isalpha, etc.) return, on success, a nonzero value which is _not_ necessarily 1. (Besides, if you believe that "if((a == b) == TRUE)" is an improvement over "if(a == b)", why stop there? Why not use "if(((a == b) == TRUE) == TRUE)"?) A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable, or as the return value from a Boolean function, never in a comparison. The preprocessor macros TRUE and FALSE (and, of course, NULL) are used for code readability, not because the underlying values might ever change. That "true" is 1 and "false" 0 is guaranteed by the language. (See also question 8.) References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5; Achilles and the Tortoise. 75. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. Although many people might have wished otherwise, the ANSI standard says that enumerations may be freely intermixed with integral types, without errors. (If such intermixing were disallowed without explicit casts, judicious use of enums could catch certain programming errors.) The primary advantages of enums are that the numeric values are automatically assigned, and that a debugger may be able to display the symbolic values when enum variables are examined. (A compiler may also generate nonfatal warnings when enums and ints are indiscriminately mixed, since doing so can still be considered bad style even though it is not strictly illegal). A disadvantage is that the programmer has little control over the size. References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 . Section 12. Operating System Dependencies 76. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. The delivery of characters from a "keyboard" to a C program is a function of the operating system in use, and cannot be standardized by the C language. If you are using curses, use its cbreak() function. Under UNIX, use ioctl to play with the terminal driver modes (CBREAK or RAW under "classic" versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or Posix systems). Under MS-DOS, use getch(). Under other operating systems, you're on your own. Beware that some operating systems make this sort of thing impossible, because character collection into input lines is done by peripheral processors not under direct control of the CPU running your program. Operating system specific questions are not appropriate for comp.lang.c . Many common questions are answered in frequently- asked questions postings in such groups as comp.unix.questions and comp.os.msdos.programmer . Note that the answers are often not unique even across different variants of Unix. Bear in mind when answering system-specific questions that the answer that applies to your system may not apply to everyone else's. References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1. 77. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. Some versions of curses have a nodelay() function. Depending on your system, you may also be able to use "nonblocking I/O", or a system call named "select", or the FIONREAD ioctl, or kbhit(), or rdchk(), or the O_NDELAY option to open() or fcntl(). 78. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname, or it may contain nothing. You may be able to duplicate the command language interpreter's search path logic to locate the executable if the name in argv[0] is present but incomplete. However, there is no guaranteed or portable solution. 79. How can a process change an environment variable in its caller? A: In general, it cannot. Different operating systems implement name/value functionality similar to the Unix environment in many different ways. Whether the "environment" can be usefully altered by a running program, and if so, how, is entirely system-dependent. Under Unix, a process can modify its own environment (some systems provide setenv() and/or putenv() functions to do this), and the modified environment is usually passed on to any child processes, but it is _not_ propagated back to the parent process. (The environment of the parent process can only be altered if the parent is explicitly set up to listen for some kind of change requests. The conventional execution of the BSD "tset" program in .profile and .login files effects such a scheme.) 80. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and several others supply chsize(), but there is no truly portable solution. Section 13. Stdio 81. Why does errno contain ENOTTY after a call to printf? A: Many implementations of the stdio package adjust their behavior slightly if stdout is a terminal. To make the determination, these implementations perform an operation which fails (with ENOTTY) if stdout is not a terminal. Although the output operation goes on to complete successfully, errno still contains ENOTTY. This behavior can be mildly confusing, but it is not strictly incorrect, because it is only meaningful for a program to inspect the contents of errno after an error has occurred (that is, after a library function that sets errno on error has returned an error code). Reference: CT&P Sec. 5.4 p. 73. 82. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) whenever output should definitely be visible. Several mechanisms attempt to perform the fflush for you, at the "right time," but they tend to apply only when stdout is a terminal. (See question 81.) 83. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. In particular, "\n" in a format string does not mean "expect a newline", it means "discard all whitespace". But the only way to discard all whitespace is to continue reading the stream until a non-whitespace character is seen (which is then left in the buffer for the next input), so the effect is that it keeps going until it sees a nonblank line. 84. So what should I use instead? A: You could use a "%c" format, which will read one character that you can then manually compare against a newline; or "%*c" and no variable if you're willing to trust the user to hit a newline; or "%*[^\n]%*c" to discard everything up to and including the newline. Usually the best solution is to use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. 85. How can I recover the file name given an open file descriptor? A: This problem is, in general, insoluble. Under Unix, for instance, a scan of the entire disk, (perhaps requiring special permissions) would be required, and would fail if the file descriptor were a pipe (and could give a misleading answer for a file with multiple links). It is best to remember the names of open files yourself (perhaps with a wrapper function around fopen). Section 14. Style 86. Here's a neat trick: if(!strcmp(s1, s2)) Is this good style? A: No. This is a classic example of C minimalism carried to an obnoxious degree. The test succeeds if the two strings are equal, but its form strongly suggests that it tests for inequality. A much better solution is to use a macro: #define Streq(s1, s2) (strcmp(s1, s2) == 0) 87. What's the best style for code layout in C? A: K&R, while providing the example most often copied, also supply a good excuse for avoiding it: The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently. It is more important that the layout chosen be consistent (with itself, and with nearby or common code) than that it be "perfect." If your coding environment (i.e. local custom or company policy) does not suggest a style, and you don't feel like inventing your own, just copy K&R. (The tradeoffs between various indenting and brace placement options can be exhaustively and minutely examined, but don't warrant repetition here. See also the Indian Hill Style Guide.) Reference: K&R Sec. 1.2 p. 10. 88. Where can I get the "Indian Hill Style Guide" and other coding standards? A: Various documents are available for anonymous ftp from: Site: File or directory: cs.washington.edu ~ftp/pub/cstyle.tar.Z (128.95.1.4) (the updated Indian Hill guide) cs.toronto.edu doc/programming giza.cis.ohio-state.edu pub/style-guide prep.ai.mit.edu pub/gnu/standards.text Section 15. Miscellaneous 89. What can I safely assume about the initial values of variables which are not explicitly initialized? If global variables start out as "zero," is that good enough for null pointers and floating- point zeroes? A: Variables (and arrays) with "static" duration (that is, those declared outside of functions, and those declared with the storage class static), are guaranteed initialized to zero, as if the programmer had typed "= 0". Therefore, such variables are initialized to the null pointer (of the correct type) if they are pointers, and to 0.0 if they are floating-point. This requirement means that compilers and linkers on machines which use nonzero internal representations for null pointers and/or floating-point zeroes cannot necessarily make use of uninitialized, 0-filled memory, but must emit explicit initializers for these values (rather as if the programmer had). Variables with "automatic" duration (i.e. local variables without the static storage class) start out containing garbage, unless they are explicitly initialized. Nothing useful can be predicted about the garbage. Dynamically-allocated memory obtained with malloc and realloc is also likely to contain garbage, and must be initialized by the calling program, as appropriate. Memory obtained with calloc contains all-bits-0, but this is not necessarily useful for pointer or floating-point values (see question 57). 90. Can someone tell me how to write itoa (the inverse of atoi)? A: Just use sprintf. (You'll have to allocate space for the result somewhere anyway; see questions 51 and 52. Don't worry that sprintf may be overkill, potentially wasting run time or code space; it works well in practice.) References: K&R I Sec. 3.6 p. 60; K&R II Sec. 3.6 p. 64. 91. I know that the library routine localtime will convert a time_t into a broken-down struct tm, and that ctime will convert a time_t to a printable string. How can I perform the inverse operations of converting a struct tm or a string into a time_t? A: ANSI C specifies a library routine, mktime, which converts a struct tm to a time_t. Several public-domain versions of this routine are available in case your compiler does not support it yet. Converting a string to a time_t is harder, because of the wide variety of date and time formats which should be parsed. Public- domain routines have been written for performing this function, as well (see, for example, the file partime.c, widely distributed with the RCS package), but they are less likely to become standardized. References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI Sec. 4.12.2.3 . 92. How can I write data files which can be read on other machines with different word size, byte order, or floating point formats? A: The best solution is to use text files (usually ASCII), written with fprintf and read with fscanf or the like. (Similar advice also applies to network protocols.) Be very skeptical of arguments which imply that text files are too big, or that reading and writing them is too slow. Not only is their efficiency frequently acceptable in practice, but the advantages of being able to manipulate them with standard tools can be overwhelming. If the binary format is being imposed on you by an existing program, first see if you can get that program changed to use a more portable format. If you must use a binary format, you can improve portability, and perhaps take advantage of prewritten I/O libraries, by making use of standardized formats such as Sun's XDR, OSI's ASN.1, or CCITT's X.409 . 93. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: Standard headers exist in part so that definitions appropriate to your compiler, operating system, and processor can be supplied. You cannot just pick up a copy of someone else's header file and expect it to work, unless that person is using exactly the same environment. Ask your compiler vendor why the file was not provided (or to send a replacement copy). 94. How can I call Fortran (BASIC, Pascal, ADA, lisp) functions from C? (And vice versa?) A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use, and may not be possible at all. Read your compiler documentation very carefully; sometimes there is a "mixed-language programming guide," although the techniques for passing arguments and ensuring correct run-time startup are often arcane. 95. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available: p2c written by Dave Gillespie, and posted to comp.sources.unix in March, 1990 (Volume 21). ptoc another comp.sources.unix contribution, this one written in Pascal (comp.sources.unix, Volume 10, also patches in Volume 13?). f2c jointly developed by people from Bell Labs, Bellcore, and Carnegie Mellon. To find about f2c, send the mail message "send index from f2c" to netlib@research.att.com or research!netlib. (It is also available via anonymous ftp on research.att.com, in directory dist/f2c.) The following companies sell various translation tools and services: Cobalt Blue 2940 Union Ave., Suite C San Jose, CA 95124 USA (+1) 408 723 0474 Promula Development Corp. 3620 N. High St., Suite 301 Columbus, OH 43214 USA (+1) 614 263 5454 Lexeme Corporation Richard Cox 4 Station Square, #250 Commerce Court Pittsburgh, PA 15219-1119 USA (+1) 412 281 5454 Micro-Processor Services Inc 92 Stone Hurst Lane Dix Hills, NY 11746 USA (+1) 519 499 4461 The comp.sources.unix archives also contain converters between "K&R" C and ANSI C. 96. Where can I get copies of all these public-domain programs? A: If you have access to Usenet, see the regular postings in the comp.sources.unix and comp.sources.misc newsgroups, which describe, in some detail, the archiving policies and how to retrieve copies. The usual approach is to use anonymous ftp and/or uucp from a central, public-spirited site, such as uunet.uu.net (192.48.96.2). However, this article cannot track or list all of the available archive sites and how to access them. The comp.archives newsgroup contains numerous announcements of anonymous ftp availability of various items. The "archie" mailserver can tell you which anonymous ftp sites have which packages; send the mail message "help" to archie@quiche.cs.mcgill.ca for information. 97. Where can I get the winners of old Obfuscated C Contests? When will the next contest be held? A: Send mail to {pacbell,uunet,utzoo}!hoptoad!obfuscate . The contest is usually announced in March, with entries due in May. Contest announcements are posted in several obvious places. The winning entries are archived on uunet (see question 96). 98. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good, mostly because of the possibility of accidentally leaving comments unclosed by including the characters "/*" within them. For this reason, it is usually better to "comment out" large sections of code, which might contain comments, with #ifdef or #if 0 (but see question 34). The character sequences /* and */ are not special within double- quoted strings, and do not therefore introduce comments, because a program (particularly one which is generating C code as output) might want to print them. It is hard to imagine why anyone would want or need to place a comment inside a quoted string. It is easy to imagine a program needing to print "/*". Reference: ANSI Rationale Sec. 3.1.9 p. 33. 99. How can I make this code more efficient? A: Efficiency, though a favorite comp.lang.c topic, is not important nearly as often as people tend to think it is. Most of the code in most programs is not time-critical. When code is not time- critical, it is far more important that it be written clearly and portably than that it be written maximally efficiently. (Remember that computers are very, very fast, and that even "inefficient" code can run without apparent delay.) It is notoriously difficult to predict what the "hot spots" in a program will be. When efficiency is a concern, it is important to use profiling software to determine which parts of the program deserve attention. Often, actual computation time is swamped by peripheral tasks such as I/O and memory allocation, which can be sped up by using buffering and cacheing techniques. For the small fraction of code that is time-critical, it is vital to pick a good algorithm; it is much less important to "microoptimize" the coding details. Source-level optimizations rarely make significant improvements, and often render code opaque. Many of the "efficient coding tricks" which are frequently suggested (e.g. substituting shift operators for multiplication by powers of two) are performed automatically by even simpleminded compilers. Heavyhanded "optimization" attempts can make code so bulky that performance is degraded. If the performance of your code is so important that you are willing to invest programming time in source-level optimizations, you would be better served by buying the best optimizing compiler you can afford (compilers can perform optimizations that are impossible at the source level). It is not the intent here to suggest that efficiency can be completely ignored. Most of the time, however, by simply paying attention to good algorithm choices, implementing them clearly and obviously, and avoiding obviously inefficient blunders (i.e. shun O(n**3) implementations of O(n**2) algorithms), perfectly acceptable results can be achieved. 100. Are pointers really faster than arrays? Do function calls really slow things down? Is i++ faster than i = i + 1? A: Precise answers to these and many similar questions depend of course on the processor and compiler in use. If you simply must know, you'll have to time test programs carefully. (Often the differences are so slight that hundreds of thousands of iterations are required even to see them. Check the compiler's assembly language output, if available, to see if two purported alternatives aren't compiled identically.) It is "usually" faster to march through large arrays with pointers rather than array subscripts, but for some processors the reverse is true. Function calls, though obviously incrementally slower than in-line code, contribute so much to modularity and code clarity that there is rarely good reason to avoid them. (Actually, by reducing bulk, functions can improve performance.) Before rearranging expressions such as i = i + 1, remember that you are dealing with a C compiler, not a keystroke-programmable calculator. A good compiler will generate identical code for i++, i += 1, and i = i + 1. The reasons for using i++ or i += 1 over i = i + 1 have to do with style, not efficiency. 101. My floating-point calculations are acting strangely and giving me different answers on different machines. A: Most digital computers use floating-point formats which provide a close but by no means exact simulation of real number arithmetic. Among other things, the associative and distributive laws do not hold completely (i.e. order of operation may be important, repeated addition is not necessarily equivalent to multiplication, and underflow or cumulative precision loss is often a problem). Don't assume that floating-point results will be exact, and especially don't assume that floating-point values can be compared for equality. (Don't throw haphazard "fuzz factors" in, either.) These problems are no worse for C than they are for any other computer language. Floating-point semantics are usually defined as "however the processor does them;" otherwise a compiler for a machine without the "right" model would have to do prohibitively expensive emulations. This article cannot begin to list the pitfalls associated with, and workarounds appropriate for, floating-point work. A good programming text should cover the basics. (Beware, though, that subtle problems can occupy numerical analysts for years.) Do make sure that you have #included <math.h>, and correctly declared other functions returning double. References: K&P Sec. 6 pp. 115-8. 102. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C (and Ritchie's original PDP-11 compiler), leave out floating point support if it looks like it will not be needed. In particular, the non- floating-point versions of printf and scanf save space by not including code to handle %e, %f, and %g. It happens that Turbo C's heuristics for determining whether the program uses floating point are occasionally insufficient, and the programmer must sometimes insert one dummy explicit floating-point operation to force loading of floating-point support. In general, questions about a particular compiler are inappropriate for comp.lang.c . Problems with PC compilers, for instance, will find a more receptive audience in a PC newsgroup (e.g. comp.os.msdos.programmer). 103. This program crashes before it even runs! (When single-stepping with a debugger, it dies before the first statement in main.) A: You probably have one or more very large (kilobyte or more) local arrays. Many systems have fixed-size stacks, and those which perform dynamic stack allocation automatically (e.g. Unix) are often confused when the stack tries to grow by a huge chunk all at once. It is often better to declare large arrays with static duration (unless of course you need a fresh set with each recursive call). 104. Does anyone have a C compiler test suite I can use? A: Plum Hall (1 Spruce Ave., Cardiff, NJ 08232, USA), among others, sells one. 105. Where can I get a YACC grammar for C? A: The definitive grammar is of course the one in the ANSI standard. Several copies are floating around; keep your eyes open. There is one on uunet.uu.net (192.48.96.2) in net.sources/ansi.c.grammar.Z . The FSF's GNU C compiler contains a grammar, as does the appendix to K&R II. References: ANSI Sec. A.2 . 106. How do you pronounce "char"? What's that funny name for the "#" character? A: You can pronounce the C keyword "char" like the English words "char," "care," or "car;" the choice is arbitrary. Bell Labs once proposed the (now obsolete) term "octothorpe" for the "#" character. Trivia questions like these aren't any more pertinent for comp.lang.c than they are for any of the other groups they frequently come up in. You can find lots of information in the net.announce.newusers frequently-asked questions postings, the "jargon file" (also published as _The Hacker's Dictionary_), and the official Usenet ASCII pronunciation list, maintained by Maarten Litmaath. (The pronunciation list also appears in the jargon file under ASCII, as well as in the comp.unix frequently-asked questions list.) 107. Where can I get extra copies of this list? What about back issues? A: For now, just pull it off the net; it is normally posted to comp.lang.c on the first of each month, with an Expiration: line which should keep it around all month. Eventually, it may be available for anonymous ftp, or via a mailserver. (Note that the size of the list is monotonically increasing; older copies are obsolete and don't contain much, except the occasional typo, that the current list doesn't.) Bibliography ANSI American National Standard for Information Systems -- Programming Language -- C, ANSI X3.159-1989 (see question 30). H&S Samuel P. Harbison and Guy L. Steele, C: A Reference Manual, Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0. (A third edition has recently been released.) PCS Mark R. Horton, Portable C Software, Prentice Hall, 1990, ISBN 0-13-868050-7. K&P Brian W. Kernighan and P.J. Plaugher, The Elements of Programming Style, Second Edition, McGraw-Hill, 1978, ISBN 0- 07-034207-5. K&R I Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall, 1978, ISBN 0-13-110163-3. K&R II Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Second Edition, Prentice Hall, 1988, ISBN 0-13- 110362-8, 0-13-110370-9. CT&P Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989, ISBN 0-201-17928-8. There is a more extensive bibliography in the revised Indian Hill style guide (see question 88). Acknowledgements Thanks to Sudheer Apte, Joe Buehler, Raymond Chen, Christopher Calabrese, James Davies, Norm Diamond, Ray Dunn, Stephen M. Dunn, Bjorn Engsig, Ron Guilmette, Doug Gwyn, Tony Hansen, Joe Harrington, Guy Harris, Blair Houghton, Kirk Johnson, Andrew Koenig, John Lauro, Christopher Lott, Tim McDaniel, Evan Manning, Mark Moraes, Francois Pinard, randall@virginia, Pat Rankin, Rich Salz, Chip Salzenberg, Paul Sand, Doug Schmidt, Patricia Shanahan, Peter da Silva, Joshua Simons, Henry Spencer, Erik Talvola, Clarke Thatcher, Chris Torek, Ed Vielmetti, Larry Virden, Freek Wiedijk, and Dave Wolverton, who have contributed, directly or indirectly, to this article. Special thanks to Karl Heuer, and particularly to Mark Brader, who (to borrow a line from Steve Johnson) have goaded me beyond my inclination, and frequently beyond my endurance, in relentless pursuit of a better FAQ list. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990, 1991 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained. The C code in this article (vstrcat, error, etc.) is public domain and may be used without restriction.
scs@adam.mit.edu (Steve Summit) (03/01/91)
[Last modified February 28, 1991 by scs.] This article contains minimal answers to the comp.lang.c frequently asked questions list. Please see the long version for more detailed explanations and references. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable or expression of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic function calls) a constant 0 with an appropriate explicit cast is required. 3. But aren't pointers the same as ints? A: Not since the early days. 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0), which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. I use the preprocessor macro "#define Nullptr(type) (type *)0 " to help me build null pointers of the correct type. A: This trick, though valid, does not buy much. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 9. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler (or the code being compiled) was probably broken. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" is a language concept whose particular internal value does not matter. A null pointer is requested in source code with the character "0". "NULL" is a preprocessor macro, which is always #defined as 0 (or (void *)0). 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. 14. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." 15. Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? A: What would such a requirement really accomplish? 16. Seriously, have any actual machines really used nonzero null pointers? A: Machines manufactured by Prime and by Honeywell-Bull, as well as Symbolics Lisp Machines, have done so. Section 2. Arrays and Pointers 17. I had the definition char x[6] in one source file, and in another I declared extern char *x. Why didn't it work? A: The declaration extern char *x simply does not match the actual definition. Use extern char x[]. 18. But I heard that char x[] was identical to char *x. A: Not at all. Arrays are not pointers. 19. You mean that a reference like x[3] generates different code depending on whether x is an array or a pointer? A: Precisely. 20. So what is meant by the "equivalence of pointers and arrays" in C? A: An identifier of type array-of-T which appears in an expression decays into a pointer to its first element; the type of the resultant pointer is pointer-to-T. 21. Why are array and pointer declarations interchangeable as function formal parameters? A: Since functions can never receive arrays as parameters, any parameter declarations which "look like" arrays are treated by the compiler as if they were pointers. 22. Someone explained to me that arrays were really just constant pointers. A: An array name is "constant" in that it cannot be assigned to, but an array is _not_ a pointer. 23. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? A: Yes, array subscripting is commutative in C. The array subscripting operation a[e] is defined as being equivalent to *((a)+(e)). 24. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 25. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. 26. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Section 3. Order of Evaluation 27. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++);" prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 28. But what about the &&, ||, and comma operators? A: There is a special exception for those operators, (as well as ?: ); left-to-right evaluation is guaranteed. Section 4. ANSI C 29. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. The Standard has also been adopted as ISO/IEC 9899:1990. 30. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for addresses. 31. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: See the full list for details. 32. What's the difference between "char const *p" and "char * const p"? A: The former is a pointer to a constant character; the latter is a constant pointer to a character. 33. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed by using either new-style (prototype) or old-style syntax consistently. 34. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (i.e. no single apostrophes), and no newlines inside quotes. 35. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which cannot be forced (by mere words in a Standard) to upgrade. 36. Whatever happened to noalias? A: It was deleted from the final versions of the standard because of widespread complaint and the near-impossibility of defining it properly. 37. What are #pragmas and what are they good for? A: The #pragma directive provides a single, well-defined "escape hatch" which can be used for extensions. Section 5. C Preprocessor 38. How can I write a generic macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 39. I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b ", but it doesn't work any more. A: Try the ANSI token-pasting operator ##. 40. What's the best way to write a multi-statement cpp macro? A: #define Func() do {stmt1; stmt2; ... } while(0) /* (no trailing ;) */ 41. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Section 6. Variable-Length Argument Lists 42. How can I write a function that takes a variable number of arguments? A: Use the <stdarg.h> header. 43. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 44. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 45. How can I discover how many arguments a function was actually called with? A: Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 46. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Section 7. Lint 47. I just typed in this program, and it's acting strangely. Can you see anything wrong with it? A: Try running lint first. 48. How can I shut off the "warning: possible pointer alignment problem" message lint gives me for each call to malloc? A: It may be easier simply to ignore the message, perhaps in an automated way with grep -v. 49. Where can I get an ANSI-compatible lint? A: See the unabridged list for two commercial products. 50. Don't ANSI function prototypes render lint obsolete? A: Not really. A good compiler may match most of lint's diagnostics; few provide all. Section 8. Memory Allocation 51. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 52. I can't get strcat to work. I tried "char *s1 = "Hello, ", *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. 53. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. 54. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 55. How does free() know how many bytes to free? A: The malloc/free package remembers the size of each block it allocates and returns. 56. Is it legal to pass a null pointer as the first argument to realloc()? A: ANSI C sanctions this usage, but several earlier implementations do not support it. 57. Is it safe to use calloc's zero-fill guarantee for pointer and floating-point values? A: calloc(m, n) is essentially equivalent to "p = malloc(m * n); memset(p, 0, m * n); ". The zero fill is all-bits-zero, and does not therefore guarantee useful zero values for pointers or floating-point values. 58. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. Section 9. Structures 59. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 60. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 61. I have a program which works correctly, but dumps core after it finishes. Why? A: Check to see if a structure type declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. See also question 103. 62. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 63. I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make the array act like it had several elements. Is this legal and/or portable? A: The ANSI C standard allows it, but only implicitly. 64. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 65. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Section 10. Declarations 66. How do you decide which integer type to use? A: If you might need large values, use long. If space is very important, use short. Otherwise, use int. 67. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 68. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. 69. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: char *(*(*a[5])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 70. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. 71. How do I initialize a pointer to a function? A: Use something like "extern int func(); int (*fp)() = func; " . 72. I've seen different methods used for calling through pointers to functions. A: The extra parentheses and explicit * are now officially optional, although some older implementations require them. Section 11. Boolean Expressions and Variables 73. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 74. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 75. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enumerations are compatible with integral types. Section 12. Operating System Dependencies 76. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 77. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 78. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 79. How can a process change an environment variable in its caller? A: In general, it cannot. 80. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and several others supply chsize(), but there is no truly portable solution. Section 13. Stdio 81. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 82. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) whenever output should definitely be visible. 83. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 84. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. 85. How can I recover the file name given an open file descriptor? A: This problem is, in general, insoluble. It is best to remember the names of open files yourself. Section 14. Style 86. Is the code "if(!strcmp(s1, s2))" good style? A: No. 87. What's the best style for code layout in C? A: There is no one "best style," but see the full list for a few suggestions. 88. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. Section 15. Miscellaneous 89. What can I safely assume about the initial values of variables which are not explicitly initialized? A: Variables with "static" duration start out as 0, as if the programmer had initialized them. Variables with "automatic" duration, and dynamically-allocated memory, start out containing garbage (with the exception of calloc). 90. Can someone tell me how to write itoa? A: Just use sprintf. 91. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 92. How can I write data files which can be read on other machines with different data formats? A: The best solution is to use text files. 93. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 94. How can I call Fortran (BASIC, Pascal, ADA, lisp) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 95. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 96. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups for information. 97. Where can I get the winners of old Obfuscated C Contests? When will the next contest be held? A: Send mail to {pacbell,uunet,utzoo}!hoptoad!obfuscate . 98. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 99. How can I make this code more efficient? A: Efficiency is not important nearly as often as people tend to think it is. Most of the time, by simply paying attention to good algorithm choices, perfectly acceptable results can be achieved. 100. Are pointers really faster than arrays? Do function calls really slow things down? A: Precise answers to these and many similar questions depend of course on the processor and compiler in use. 101. My floating-point calculations are acting strangely and giving me different answers on different machines. A: See the full list for a brief explanation, or any good programming book for a better one. 102. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 103. This program crashes before it even runs! A: Look for very large, local arrays. 104. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 105. Where can I get a YACC grammar for C? A: See the ANSI Standard, or the unabridged list. 106. How do you pronounce "char"? A: Like the English words "char," "care," or "car" (your choice). 107. Where can I get extra copies of this list? A: For now, just pull it off the net; the unabridged version is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990, 1991 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (03/15/91)
[Last modified February 28, 1991 by scs.] This article contains minimal answers to the comp.lang.c frequently- asked questions list. Please see the long version (posted on the first of each month) for more detailed explanations and references. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable or expression of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic function calls) a constant 0 with an appropriate explicit cast is required. 3. But aren't pointers the same as ints? A: Not since the early days. 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0), which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. I use the preprocessor macro "#define Nullptr(type) (type *)0 " to help me build null pointers of the correct type. A: This trick, though valid, does not buy much. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 9. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler (or the code being compiled) was probably broken. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" is a language concept whose particular internal value does not matter. A null pointer is requested in source code with the character "0". "NULL" is a preprocessor macro, which is always #defined as 0 (or (void *)0). 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. 14. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." 15. Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? A: What would such a requirement really accomplish? 16. Seriously, have any actual machines really used nonzero null pointers? A: Machines manufactured by Prime and by Honeywell-Bull, as well as Symbolics Lisp Machines, have done so. Section 2. Arrays and Pointers 17. I had the definition char x[6] in one source file, and in another I declared extern char *x. Why didn't it work? A: The declaration extern char *x simply does not match the actual definition. Use extern char x[]. 18. But I heard that char x[] was identical to char *x. A: Not at all. Arrays are not pointers. 19. You mean that a reference like x[3] generates different code depending on whether x is an array or a pointer? A: Precisely. 20. So what is meant by the "equivalence of pointers and arrays" in C? A: An identifier of type array-of-T which appears in an expression decays into a pointer to its first element; the type of the resultant pointer is pointer-to-T. 21. Why are array and pointer declarations interchangeable as function formal parameters? A: Since functions can never receive arrays as parameters, any parameter declarations which "look like" arrays are treated by the compiler as if they were pointers. 22. Someone explained to me that arrays were really just constant pointers. A: An array name is "constant" in that it cannot be assigned to, but an array is _not_ a pointer. 23. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? A: Yes, array subscripting is commutative in C. The array subscripting operation a[e] is defined as being equivalent to *((a)+(e)). 24. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 25. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. 26. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Section 3. Order of Evaluation 27. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++);" prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 28. But what about the &&, ||, and comma operators? A: There is a special exception for those operators, (as well as ?: ); left-to-right evaluation is guaranteed. Section 4. ANSI C 29. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. The Standard has also been adopted as ISO/IEC 9899:1990. 30. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for addresses. 31. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: See the full list for details. 32. What's the difference between "char const *p" and "char * const p"? A: The former is a pointer to a constant character; the latter is a constant pointer to a character. 33. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed by using either new-style (prototype) or old-style syntax consistently. 34. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (i.e. no single apostrophes), and no newlines inside quotes. 35. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which cannot be forced (by mere words in a Standard) to upgrade. 36. Whatever happened to noalias? A: It was deleted from the final versions of the standard because of widespread complaint and the near-impossibility of defining it properly. 37. What are #pragmas and what are they good for? A: The #pragma directive provides a single, well-defined "escape hatch" which can be used for extensions. Section 5. C Preprocessor 38. How can I write a generic macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 39. I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b ", but it doesn't work any more. A: Try the ANSI token-pasting operator ##. 40. What's the best way to write a multi-statement cpp macro? A: #define Func() do {stmt1; stmt2; ... } while(0) /* (no trailing ;) */ 41. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Section 6. Variable-Length Argument Lists 42. How can I write a function that takes a variable number of arguments? A: Use the <stdarg.h> header. 43. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 44. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 45. How can I discover how many arguments a function was actually called with? A: Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 46. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Section 7. Lint 47. I just typed in this program, and it's acting strangely. Can you see anything wrong with it? A: Try running lint first. 48. How can I shut off the "warning: possible pointer alignment problem" message lint gives me for each call to malloc? A: It may be easier simply to ignore the message, perhaps in an automated way with grep -v. 49. Where can I get an ANSI-compatible lint? A: See the unabridged list for two commercial products. 50. Don't ANSI function prototypes render lint obsolete? A: Not really. A good compiler may match most of lint's diagnostics; few provide all. Section 8. Memory Allocation 51. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 52. I can't get strcat to work. I tried "char *s1 = "Hello, ", *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. 53. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. 54. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 55. How does free() know how many bytes to free? A: The malloc/free package remembers the size of each block it allocates and returns. 56. Is it legal to pass a null pointer as the first argument to realloc()? A: ANSI C sanctions this usage, but several earlier implementations do not support it. 57. Is it safe to use calloc's zero-fill guarantee for pointer and floating-point values? A: calloc(m, n) is essentially equivalent to "p = malloc(m * n); memset(p, 0, m * n); ". The zero fill is all-bits-zero, and does not therefore guarantee useful zero values for pointers or floating-point values. 58. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. Section 9. Structures 59. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 60. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 61. I have a program which works correctly, but dumps core after it finishes. Why? A: Check to see if a structure type declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. See also question 103. 62. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 63. I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make the array act like it had several elements. Is this legal and/or portable? A: The ANSI C standard allows it, but only implicitly. 64. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 65. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Section 10. Declarations 66. How do you decide which integer type to use? A: If you might need large values, use long. If space is very important, use short. Otherwise, use int. 67. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 68. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. 69. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: char *(*(*a[5])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 70. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. 71. How do I initialize a pointer to a function? A: Use something like "extern int func(); int (*fp)() = func; " . 72. I've seen different methods used for calling through pointers to functions. A: The extra parentheses and explicit * are now officially optional, although some older implementations require them. Section 11. Boolean Expressions and Variables 73. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 74. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 75. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enumerations are compatible with integral types. Section 12. Operating System Dependencies 76. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 77. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 78. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 79. How can a process change an environment variable in its caller? A: In general, it cannot. 80. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and several others supply chsize(), but there is no truly portable solution. Section 13. Stdio 81. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 82. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) whenever output should definitely be visible. 83. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 84. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. 85. How can I recover the file name given an open file descriptor? A: This problem is, in general, insoluble. It is best to remember the names of open files yourself. Section 14. Style 86. Is the code "if(!strcmp(s1, s2))" good style? A: No. 87. What's the best style for code layout in C? A: There is no one "best style," but see the full list for a few suggestions. 88. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. Section 15. Miscellaneous 89. What can I safely assume about the initial values of variables which are not explicitly initialized? A: Variables with "static" duration start out as 0, as if the programmer had initialized them. Variables with "automatic" duration, and dynamically-allocated memory, start out containing garbage (with the exception of calloc). 90. Can someone tell me how to write itoa? A: Just use sprintf. 91. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 92. How can I write data files which can be read on other machines with different data formats? A: The best solution is to use text files. 93. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 94. How can I call Fortran (BASIC, Pascal, ADA, lisp) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 95. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 96. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups for information. 97. Where can I get the winners of old Obfuscated C Contests? When will the next contest be held? A: Send mail to {pacbell,uunet,utzoo}!hoptoad!obfuscate . 98. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 99. How can I make this code more efficient? A: Efficiency is not important nearly as often as people tend to think it is. Most of the time, by simply paying attention to good algorithm choices, perfectly acceptable results can be achieved. 100. Are pointers really faster than arrays? Do function calls really slow things down? A: Precise answers to these and many similar questions depend of course on the processor and compiler in use. 101. My floating-point calculations are acting strangely and giving me different answers on different machines. A: See the full list for a brief explanation, or any good programming book for a better one. 102. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 103. This program crashes before it even runs! A: Look for very large, local arrays. 104. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 105. Where can I get a YACC grammar for C? A: See the ANSI Standard, or the unabridged list. 106. How do you pronounce "char"? A: Like the English words "char," "care," or "car" (your choice). 107. Where can I get extra copies of this list? A: For now, just pull it off the net; the unabridged version is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990, 1991 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (04/02/91)
[Last modified April 2, 1991 by scs.] This article contains minimal answers to the comp.lang.c frequently- asked questions list. Please see the long version for more detailed explanations and references. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable or expression of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic function calls) a constant 0 with an appropriate explicit cast is required. 3. But aren't pointers the same as ints? A: Not since the early days. 4. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0), which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 5. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 6. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 7. I use the preprocessor macro "#define Nullptr(type) (type *)0 " to help me build null pointers of the correct type. A: This trick, though valid, does not buy much. 8. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 9. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 10. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 11. I once used a compiler that wouldn't work unless NULL was used. A: That compiler (or the code being compiled) was probably broken. 12. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" is a language concept whose particular internal value does not matter. A null pointer is requested in source code with the character "0". "NULL" is a preprocessor macro, which is always #defined as 0 (or (void *)0). 13. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. 14. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." 15. Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? A: What would such a requirement really accomplish? 16. Seriously, have any actual machines really used nonzero null pointers? A: Machines manufactured by Prime and by Honeywell-Bull, as well as Symbolics Lisp Machines, have done so. Section 2. Arrays and Pointers 17. I had the definition char x[6] in one source file, and in another I declared extern char *x. Why didn't it work? A: The declaration extern char *x simply does not match the actual definition. Use extern char x[]. 18. But I heard that char x[] was identical to char *x. A: Not at all. Arrays are not pointers. 19. You mean that a reference like x[3] generates different code depending on whether x is an array or a pointer? A: Precisely. 20. So what is meant by the "equivalence of pointers and arrays" in C? A: An lvalue of type array-of-T which appears in an expression decays into a pointer to its first element; the type of the resultant pointer is pointer-to-T. 21. Why are array and pointer declarations interchangeable as function formal parameters? A: Since functions can never receive arrays as parameters, any parameter declarations which "look like" arrays are treated by the compiler as if they were pointers. 22. Someone explained to me that arrays were really just constant pointers. A: An array name is "constant" in that it cannot be assigned to, but an array is _not_ a pointer. 23. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? A: Yes, array subscripting is commutative in C. The array subscripting operation a[e] is defined as being equivalent to *((a)+(e)). 24. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 25. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. 26. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Section 3. Order of Evaluation 27. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++);" prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 28. But what about the &&, ||, and comma operators? A: There is a special exception for those operators, (as well as ?: ); left-to-right evaluation is guaranteed. Section 4. ANSI C 29. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. The Standard has also been adopted as ISO/IEC 9899:1990. 30. How can I get a copy of the ANSI C standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for addresses. 31. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: See the full list for details. 32. What's the difference between "char const *p" and "char * const p"? A: The former is a pointer to a constant character; the latter is a constant pointer to a character. 33. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed by using either new-style (prototype) or old-style syntax consistently. 34. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (i.e. no single apostrophes), and no newlines inside quotes. 35. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which cannot be forced (by mere words in a Standard) to upgrade. 36. Whatever happened to noalias? A: It was deleted from the final versions of the standard because of widespread complaint and the near-impossibility of defining it properly. 37. What are #pragmas and what are they good for? A: The #pragma directive provides a single, well-defined "escape hatch" which can be used for extensions. Section 5. C Preprocessor 38. How can I write a generic macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 39. I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b ", but it doesn't work any more. A: Try the ANSI token-pasting operator ##. 40. What's the best way to write a multi-statement cpp macro? A: #define Func() do {stmt1; stmt2; ... } while(0) /* (no trailing ; ) */ 41. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Section 6. Variable-Length Argument Lists 42. How can I write a function that takes a variable number of arguments? A: Use the <stdarg.h> header. 43. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 44. How can I write a function analogous to scanf? A: Unfortunately, vscanf and the like are not standard. 45. How can I discover how many arguments a function was actually called with? A: Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. 46. How can I write a function which takes a variable number of arguments and passes them to some other function (which takes a variable number of arguments)? A: In general, you cannot. Section 7. Lint 47. I just typed in this program, and it's acting strangely. Can you see anything wrong with it? A: Try running lint first. 48. How can I shut off the "warning: possible pointer alignment problem" message lint gives me for each call to malloc? A: It may be easier simply to ignore the message, perhaps in an automated way with grep -v. 49. Where can I get an ANSI-compatible lint? A: See the unabridged list for two commercial products. 50. Don't ANSI function prototypes render lint obsolete? A: Not really. A good compiler may match most of lint's diagnostics; few provide all. Section 8. Memory Allocation 51. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 52. I can't get strcat to work. I tried "char *s1 = "Hello, ", *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. 53. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. 54. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 55. How does free() know how many bytes to free? A: The malloc/free package remembers the size of each block it allocates and returns. 56. Is it legal to pass a null pointer as the first argument to realloc()? A: ANSI C sanctions this usage, but several earlier implementations do not support it. 57. Is it safe to use calloc's zero-fill guarantee for pointer and floating-point values? A: calloc(m, n) is essentially equivalent to "p = malloc(m * n); memset(p, 0, m * n); ". The zero fill is all-bits-zero, and does not therefore guarantee useful zero values for pointers or floating-point values. 58. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function from which alloca was called returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. Section 9. Structures 59. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 60. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 61. I have a program which works correctly, but dumps core after it finishes. Why? A: Check to see if a structure type declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. See also question 103. 62. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 63. I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make the array act like it had several elements. Is this legal and/or portable? A: The ANSI C standard allows it, but only implicitly. 64. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 65. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Section 10. Declarations 66. How do you decide which integer type to use? A: If you might need large values, use long. If space is very important, use short. Otherwise, use int. 67. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 68. How can I define a pair of mutually referential structures? A: The obvious technique works as long as any typedef synonyms are defined outside of the struct declarations. 69. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: char *(*(*a[5])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 70. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. 71. How do I initialize a pointer to a function? A: Use something like "extern int func(); int (*fp)() = func; " . 72. I've seen different methods used for calling through pointers to functions. A: The extra parentheses and explicit * are now officially optional, although some older implementations require them. Section 11. Boolean Expressions and Variables 73. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 74. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 75. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enumerations are compatible with integral types. Section 12. Operating System Dependencies 76. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 77. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 78. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 79. How can a process change an environment variable in its caller? A: In general, it cannot. 80. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and several others supply chsize(), but there is no truly portable solution. Section 13. Stdio 81. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 82. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) whenever output should definitely be visible. 83. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 84. So what should I use instead? A: Use fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. 85. How can I recover the file name given an open file descriptor? A: This problem is, in general, insoluble. It is best to remember the names of open files yourself. Section 14. Style 86. Is the code "if(!strcmp(s1, s2))" good style? A: No. 87. What's the best style for code layout in C? A: There is no one "best style," but see the full list for a few suggestions. 88. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. Section 15. Miscellaneous 89. What can I safely assume about the initial values of variables which are not explicitly initialized? A: Variables with "static" duration start out as 0, as if the programmer had initialized them. Variables with "automatic" duration, and dynamically-allocated memory, start out containing garbage (with the exception of calloc). 90. Can someone tell me how to write itoa? A: Just use sprintf. 91. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 92. How can I write data files which can be read on other machines with different data formats? A: The best solution is to use text files. 93. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 94. How can I call Fortran (BASIC, Pascal, ADA, lisp) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 95. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 96. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups for information. 97. Where can I get the winners of old Obfuscated C Contests? When will the next contest be held? A: Send mail to {pacbell,uunet,utzoo}!hoptoad!obfuscate . 98. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 99. How can I make this code more efficient? A: Efficiency is not important nearly as often as people tend to think it is. Most of the time, by simply paying attention to good algorithm choices, perfectly acceptable results can be achieved. 100. Are pointers really faster than arrays? Do function calls really slow things down? A: Precise answers to these and many similar questions depend of course on the processor and compiler in use. 101. My floating-point calculations are acting strangely and giving me different answers on different machines. A: See the full list for a brief explanation, or any good programming book for a better one. 102. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert one dummy explicit floating-point operation to force loading of floating-point support. 103. This program crashes before it even runs! A: Look for very large, local arrays. 104. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 105. Where can I get a YACC grammar for C? A: See the ANSI Standard, or the unabridged list. 106. How do you pronounce "char"? A: Like the English words "char," "care," or "car" (your choice). 107. Where can I get extra copies of this list? A: For now, just pull it off the net; the unabridged version is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990, 1991 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.
scs@adam.mit.edu (Steve Summit) (05/01/91)
[Last modified April 29, 1991 by scs.] Certain topics come up again and again on this newsgroup. They are good questions, and the answers may not be immediately obvious, but each time they recur, much net bandwidth and reader time is wasted on repetitive responses, and on tedious corrections to the incorrect answers which are inevitably posted. This article, which is posted monthly, attempts to answer these common questions definitively and succinctly, so that net discussion can move on to more constructive topics without continual regression to first principles. No mere newsgroup article can substitute for thoughtful perusal of a full-length language reference manual. Anyone interested enough in C to be following this newsgroup should also be interested enough to read and study one or more such manuals, preferably several times. Some vendors' compiler manuals are unfortunately inadequate; a few even perpetuate some of the myths which this article attempts to refute. Several noteworthy books on C are listed in this article's bibliography. Many of the questions and answers are cross-referenced to these books, for further study by the interested and dedicated reader. If you have a question about C which is not answered in this article, please try to answer it by checking a few of the referenced books, or by asking knowledgeable colleagues, before posing your question to the net at large. There are many people on the net who are happy to answer questions, but the volume of repetitive answers posted to one question, as well as the growing number of questions as the net attracts more readers, can become oppressive. If you have questions or comments prompted by this article, please reply by mail rather than following up -- this article is meant to decrease net traffic, not increase it. Besides listing frequently-asked questions, this article also summarizes frequently-posted answers. Even if you know all the answers, it's worth skimming through this list once in a while, so that when you see one of its questions unwittingly posted, you won't have to waste time answering. This article is always being improved. Your input is welcomed. Send your comments to scs@adam.mit.edu, scs%adam.mit.edu@mit.edu, and/or mit-eddie!adam!scs; this article's From: line may be unusable. The questions answered here are divided into several categories: 1. Null Pointers 2. Arrays and Pointers 3. Order of Evaluation 4. ANSI C 5. C Preprocessor 6. Variable-Length Argument Lists 7. Lint 8. Memory Allocation 9. Structures 10. Declarations 11. Boolean Expressions and Variables 12. Operating System Dependencies 13. Stdio 14. Style 15. Miscellaneous (Fortran to C converters, YACC grammars, etc.) Herewith, some frequently-asked questions and their answers: Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: The language definition states that for each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. That is, the address-of operator & will never yield a null pointer, nor will a successful call to malloc. (malloc returns a null pointer when it fails, and this is a typical use of null pointers: as a "special" pointer value with some other meaning, usually "not allocated" or "not pointing anywhere yet.") A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere (that is, at some random object, or at a garbage or unallocated address). See also questions 46, 52, and 82. As mentioned in the definition above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different. Although programmers need not know the internal values, the compiler must always be informed which type of null pointer is required, so it can make the distinction if necessary (see below). References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38. 2. How do I "get" a null pointer in my programs? A: According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal: char *p = 0; if(p != 0) However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. For instance, the Unix system call "execl" takes a variable-length, null- pointer-terminated list of character pointer arguments. To generate a null pointer in a function call context, an explicit cast is typically required: execl("/bin/sh", "sh", "-c", "ls", (char *)0); If the (char *) cast were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong.) When function prototypes are in scope, argument passing becomes an "assignment context," and most casts may safely be omitted, since the prototype tells the compiler that a pointer is required, and of which type, enabling it to correctly cast unadorned 0's. Function prototypes cannot provide the types for variable arguments in variable-length argument lists, however, so explicit casts are still required for those arguments. It is safest always to cast null pointer function arguments, to guard against varargs functions or those without prototypes, to allow interim use of non-ANSI compilers, and to demonstrate that you know what you are doing. Summary: Unadorned 0 okay: Explicit cast required: initialization function call, no prototype in scope assignment variable argument in comparison varargs function call function call, prototype in scope, fixed argument References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI Sec. 3.2.2.3 . 3. What is NULL and how is it #defined? A: As a matter of style, many people prefer not to have unadorned 0's scattered throughout their programs. For this reason, the preprocessor macro NULL is #defined (by <stdio.h> or <stddef.h>), with value 0 (or (void *)0, about which more later). A programmer who wishes to make explicit the distinction between 0 the integer and 0 the null pointer can then use NULL whenever a null pointer is required. This is a stylistic convention only; the preprocessor turns NULL back to 0 which is then recognized by the compiler (in pointer contexts) as before. In particular, a cast may still be necessary before NULL (as before 0) in a function call argument. (The table under question 2 above applies for NULL as well as 0.) NULL should _only_ be used for pointers; see question 8. References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38, Rationale Sec. 4.1.5 p. 74. 4. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: Programmers should never need to know the internal representation(s) of null pointers, because they are normally taken care of by the compiler. If a machine uses a nonzero bit pattern for null pointers, it is the compiler's responsibility to generate it when the programmer requests, by writing "0" or "NULL," a null pointer. Therefore, #defining NULL as 0 on a machine for which internal null pointers are nonzero is as valid as on any other, because the compiler must (and can) still generate the machine's correct null pointers in response to unadorned 0's seen in pointer contexts. 5. If NULL were defined as follows: #define NULL (char *)0 wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. The suggested #definition would make uncast NULL arguments to functions expecting pointers to characters to work correctly, but pointer arguments to other types would still be problematical, and legal constructions such as FILE *fp = NULL; could fail. Nevertheless, ANSI C allows the alternate #define NULL (void *)0 definition for NULL. Besides helping incorrect programs to work (but only on machines with homogeneous pointers, thus questionably valid assistance) this definition may catch programs which use NULL incorrectly (e.g. when the ASCII NUL character was really intended). 6. I use the preprocessor macro #define Nullptr(type) (type *)0 to help me build null pointers of the correct type. A: This trick, though popular in some circles, does not buy much. It is not needed in assignments and comparisons; see question 2. It does not even save keystrokes. Its use suggests to the reader that the author is shaky on the subject of null pointers, and requires the reader to check the #definition of the macro, its invocations, and _all_ other pointer usages much more carefully. 7. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: When C requires the boolean value of an expression (in the if, while, for, and do statements, and with the &&, ||, !, and ?: operators), a false value is produced when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes if(expr) where "expr" is any expression at all, the compiler essentially acts as if it had been written as if(expr != 0) Substituting the trivial pointer expression "p" for "expr," we have if(p) is equivalent to if(p != 0) and this is a comparison context, so the compiler can tell that the (implicit) 0 is a null pointer, and use the correct value. There is no trickery involved here; compilers do work this way, and generate identical code for both statements. The internal representation of a pointer does _not_ matter. The boolean negation operator, !, can be described as follows: !expr is essentially equivalent to expr?0:1 It is left as an exercise for the reader to show that if(!p) is equivalent to if(p == 0) "Abbreviations" such as if(p), though perfectly legal, are considered by some to be bad style. See also question 68. References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and 3.6.5 . 8. If "NULL" and "0" are equivalent, which should I use? A: Many programmers believe that "NULL" should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding "NULL" and "0" is only compounded by hiding "0" behind a #definition, and prefer to use unadorned "0" instead. There is no one right answer. C programmers must understand that "NULL" and "0" are interchangeable and that an uncast "0" is perfectly acceptable in initialization, assignment, and comparison contexts. Any usage of "NULL" (as opposed to "0") should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's. NULL should _not_ be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (ANSI allows the #definition of NULL to be (void *)0, which will not work in non-pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition #define NUL '\0' if you must. Reference: K&R II Sec. 5.4 p. 102. 9. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. Although symbolic constants are often used in place of numbers because the numbers might change, this is _not_ the reason that NULL is used in place of 0. Once again, the language guarantees that source-code 0's (in pointer contexts) generate null pointers. NULL is used only as a stylistic convention. 10. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: When the term "null" or "NULL" is casually used, one of several things may be meant: 1. The conceptual null pointer, the abstract language concept defined in question 1. It is implemented with... 2. The internal (or run-time) representation of a null pointer, which may or may not be all-bits-0 and which may be different for different pointer types. The actual values should be of concern only to compiler writers. Authors of C programs never see them, since they use... 3. The source code syntax for null pointers, which is the single character "0". It is often hidden behind... 4. The NULL macro, which is #defined to be "0" or "(void *)0". Finally, as a red herring, we have... 5. The ASCII null character (NUL), which does have all bits zero, but has no relation to the null pointer except in name. This article always uses the phrase "null pointer" (in lower case) for sense 1, the character "0" for sense 3, and the capitalized word "NULL" for sense 4. 11. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: C programmers traditionally like to know more than they need to about the underlying machine implementation. The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. Finally, the distinction between the several uses of the term "null" (listed above) is often overlooked. One good way to wade out of the confusion is to imagine that C had a keyword (perhaps "nil", like Pascal) with which null pointers were requested. The compiler could either turn "nil" into the correct type of null pointer, when it could determine the type from the source code (as it does with 0's in reality), or complain when it could not. Now, in fact, in C the keyword for a null pointer is not "nil" but "0", which works almost as well, except that an uncast "0" in a non-pointer context generates an integer zero instead of an error message, and if that uncast 0 was supposed to be a null pointer, the code may not work. 12. I'm still confused. I just can't understand all this null pointer stuff. A: Follow these two simple rules: 1. When you want to refer to a null pointer in source code, use "0" or "NULL". 2. If the usage of "0" or "NULL" is an argument in a function call, cast it to the pointer type expected by the function being called. The rest of the discussion has to do with other people's misunderstandings, or with the internal representation of null pointers, which you shouldn't need to know. Understand questions 1, 2, and 3, and consider 8 and 11, and you'll do fine. 13. Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? A: If for no other reason, doing so would be ill-advised because it would unnecessarily constrain implementations which would otherwise naturally represent null pointers by special, nonzero bit patterns, particularly when those values would trigger automatic hardware traps for invalid accesses. Besides, what would this requirement really accomplish? Proper understanding of null pointers does not require knowledge of the internal representation, whether zero or nonzero. Assuming that null pointers are internally zero does not make any code easier to write (except for a certain ill-advised usage of calloc; see question 52). Known-zero internal pointers would not obviate casts in function calls, because the _size_ of the pointer might still be different from that of an int. (If "nil" were used to request null pointers rather than "0," as mentioned in question 11, the urge to assume an internal zero representation would not even arise.) 14. Seriously, have any actual machines really used nonzero null pointers? A: "Certain Prime computers use a value different from all- bits-0 to encode the null pointer. Also, some large Honeywell-Bull machines use the bit pattern 06000 to encode the null pointer." -- Portable C, by H. Rabinowitz and Chaim Schaap, Prentice-Hall, 1990, page 147. The "certain Prime computers" were the segmented 50 series, which used segment 07777, offset 0 for the null pointer, at least for PL/I. Later models used segment 0, offset 0 for null pointers in C, necessitating new instructions such as TCNP (Test C Null Pointer), evidently as a sop to all the extant poorly-written C code which made incorrect assumptions. The Symbolics Lisp Machine, a tagged architecture, does not even have conventional numeric pointers; it uses the pair <NIL, 0> (basically a nonexistent <object, offset> handle) as a C null pointer. Section 2. Arrays and Pointers 15. I had the definition char x[6] in one source file, and in another I declared extern char *x. Why didn't it work? A: The declaration extern char *x simply does not match the actual definition. The type "pointer-to-type-T" is not the same as "array-of-type-T." Use extern char x[]. References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5. 16. But I heard that char x[] was identical to char *x. A: Not at all. (What you heard has to do with formal parameters to functions; see question 19.) Arrays are not pointers. The declaration "char a[6];" requests that space for six characters be set aside, to be known by the name "a." That is, there is a location named "a" at which six characters can sit. The declaration "char *p;" on the other hand, requests a place which holds a pointer. The pointer is to be known by the name "p," and can point to any char (or contiguous array of chars) anywhere. As usual, a picture is worth a thousand words. The statements char a[] = "hello"; char *p = "world"; would result in data structures which could be represented like this: +---+---+---+---+---+---+ a: | h | e | l | l | o |\0 | +---+---+---+---+---+---+ +-----+ +---+---+---+---+---+---+ p: | *======> | w | o | r | l | d |\0 | +-----+ +---+---+---+---+---+---+ 17. You mean that a reference like x[3] generates different code depending on whether x is an array or a pointer? A: Precisely. Referring back to the sample declarations in the previous question, when the compiler sees the expression a[3], it emits code to start at the location "a," move three past it, and fetch the character there. When it sees the expression p[3], it emits code to start at the location "p," fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to. In the example above, both a[3] and p[3] happen to be the character 'l', but the compiler gets there differently. (See also question 93.) 18. So what is meant by the "equivalence of pointers and arrays" in C? A: Much of the confusion surrounding pointers in C can be traced to a misunderstanding of this statement. Saying that arrays and pointers are "equivalent" does not by any means imply that they are interchangeable. "Equivalence" refers to the following key definition: An lvalue of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T. (The exceptions are when the array is the operand of the sizeof() operator or of the & operator, or is a literal string initializer for a character array.) As a consequence of this definition, there is not really any difference in the behavior of the "array subscripting" operator [] as it applies to arrays and pointers. In an expression of the form a[i], the array reference "a" decays into a pointer, following the rule above, and is then subscripted exactly as would be a pointer variable in the expression p[i]. In either case, the expression x[i] (where x is an array or a pointer) is, by definition, exactly equivalent to *((x)+(i)). References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec. 5.4.1 p. 93; ANSI Sec. 3.3.2.1, Sec. 3.3.6 . 19. Then why are array and pointer declarations interchangeable as function formal parameters? A: Since arrays decay immediately into pointers, an array is never actually passed to a function. Therefore, any parameter declarations which "look like" arrays, e.g. f(a) char a[]; are treated by the compiler as if they were pointers, since that is what the function will receive if an array is passed: f(a) char *a; This conversion holds only within function formal parameter declarations, nowhere else. If this conversion bothers you, avoid it; many people have concluded that the confusion it causes outweighs the small advantage of having the declaration "look like" the call and/or the uses within the function. References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3 pp. 33-4. 20. Someone explained to me that arrays were really just constant pointers. A: That person did you a disservice. An array name is "constant" in that it cannot be assigned to, but an array is _not_ a pointer, as the discussion and pictures in question 16 should make clear. 21. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? A: Yes, Virginia, array subscripting is commutative in C. This curious fact follows from the pointer definition of array subscripting, namely that a[e] is exactly equivalent to *((a)+(e)), for _any_ expression e and primary expression a, as long as one of them is a pointer expression and one is integral. This unsuspected commutativity is often mentioned in C texts as if it were something to be proud of, but it finds no useful application outside of the Obfuscated C Contest (see question 90). 22. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays can be confusing, and must be treated carefully. (The confusion is heightened by the existence of incorrect compilers, including some versions of pcc and pcc-derived lint's, which improperly accept assignments of multi-dimensional arrays to multi-level pointers.) If you are passing a two-dimensional array to a function: int array[YSIZE][XSIZE]; f(array); the function's declaration should match: f(int a[][XSIZE]) {...} or f(int (*ap)[XSIZE]) {...} /* ap is a pointer to an array */ In the first declaration, the compiler performs the usual implicit parameter rewriting of "array of array" to "pointer to array;" in the second form the pointer declaration is explicit. Since the called function does not allocate space for the array, it does not need to know the overall size, so the number of "rows," YSIZE, can be omitted. The "shape" of the array is still important, so the "column" dimension XSIZE (and, for 3- or more dimensional arrays, the intervening ones) must be included. If a function is already declared as accepting a pointer to a pointer, it is probably incorrect to pass a two-dimensional array directly to it. 23. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. Arrays of type T decay into pointers to type T, which is convenient; subscripting or incrementing the resultant pointer accesses the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally only useful when operating on multidimensional arrays, if at all. (See question 22 above.) When people speak casually of a pointer to an array, they usually mean a pointer to its first element. If you really need to declare a pointer to an entire array, use something like "int (*ap)[N];" where N is the size of the array. (See also question 63.) If the size of the array is unknown, N can be omitted, but the resulting type, "pointer to array of unknown size," is useless. 24. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." The resulting "ragged" array can save space, although it is not necessarily contiguous in memory as a real array would be. Here is a two-dimensional example: int **array = (int **)malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array[i] = (int *)malloc(ncolumns * sizeof(int)); (In "real" code, of course, malloc should be declared correctly, and each return value checked.) You can keep the array's contents contiguous, while making later reallocation of individual rows difficult, with a bit of explicit pointer arithmetic: int **array = (int **)malloc(nrows * sizeof(int *)); array[0] = (int *)malloc(nrows * ncolumns * sizeof(int)); for(i = 1; i < nrows; i++) array[i] = array[0] + i * ncolumns; In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: array[i][j]. If the double indirection implied by the above schemes is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array: int *array = (int *)malloc(nrows * ncolumns * sizeof(int)); However, you must now perform subscript calculations manually, accessing the i,jth element with array[i * ncolumns + j]. (A macro can hide the explicit calculation, but invoking it then requires parentheses and commas which don't look exactly like multidimensional array subscripts.) Section 3. Order of Evaluation 25. Under my compiler, the code int i = 7; printf("%d\n", i++ * i++); prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: Although the postincrement and postdecrement operators ++ and -- perform the operations after yielding the former value, many people misunderstand the implication of "after." It is _not_ guaranteed that the operation is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered "finished" (before the next "sequence point," in ANSI C's terminology). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards. The behavior of code which contains ambiguous or undefined side effects (including ambiguous embedded assignments) has always been undefined. (Note, too, that a compiler's choice, especially under ANSI rules, for "undefined behavior" may be to refuse to compile the code.) Don't even try to find out how your compiler implements such things (contrary to the ill-advised exercises in many C textbooks); as K&R wisely point out, "if you don't know _how_ they are done on various machines, that innocence may help to protect you." References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1. (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.) 26. But what about the &&, ||, and comma operators? I see code like "if((c = getchar()) == EOF || c == '\n')" ... A: There is a special exception for those operators, (as well as ?: ); each of them does imply a sequence point (i.e. left-to-right evaluation is guaranteed). Any book on C should make this clear. References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55, CT&P Sec. 3.7 pp. 46-7. Section 4. ANSI C 27. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, including several widespread public reviews, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardizes existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the much-lambasted trigraph sequences). The ANSI C standard also formalizes the C run-time library support routines. The published Standard includes a "Rationale," which explains many of its decisions, and discusses a number of subtle points, including several of those covered here. (The Rationale is "not part of ANSI Standard X3.159-1989, but is included for information only.") The Standard has been adopted as an international standard, ISO/IEC 9899:1990, although the Rationale is currently not included. 28. How can I get a copy of the Standard? A: Copies are available from American National Standards Institute 1430 Broadway New York, NY 10018 USA (+1) 212 642 4900 or Global Engineering Documents 2805 McGaw Avenue Irvine, CA 92714 USA (+1) 714 261 1455 (800) 854 7179 (U.S. & Canada) The cost from ANSI is $50.00, plus $6.00 shipping. Quantity discounts are available. (Note that ANSI derives revenues to support its operations from the sale of printed standards, so electronic copies are _not_ available.) The Rationale, by itself, has been printed by Silicon Press, ISBN 0-929306-07-4. 29. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: Two programs, protoize and unprotoize, convert back and forth between prototyped and "old style" function definitions and declarations. (These programs do _not_ handle full-blown translation between "Classic" C and ANSI C.) These programs exist as patches to the FSF GNU C compiler, gcc. Look for the file protoize-1.39.0 in pub/gnu at prep.ai.mit.edu (18.71.0.38), or at several other FSF archive sites. Several prototype generators exist, many as modifications to lint. (See also question 89.) 30. What's the difference between "char const *p" and "char * const p"? A: "char const *p" is a pointer to a constant character (you can't change the character); "char * const p" is a constant pointer to a (variable) character (i.e. you can't change the pointer). (Read these "inside out" to understand them. See question 63.) 31. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". Old C (and ANSI C, in the absence of prototypes) silently promotes floats to doubles when passing them as arguments, and arranges that doubles being passed are coerced back to floats if the formal parameters are declared that way. The problem can be fixed either by using new-style syntax consistently in the definition: int func(float x) { ... } or by changing the new-style prototype declaration to match the old-style definition: extern int func(double); (In this case, it would be clearest to change the old-style definition to use double as well, as long as the address of that parameter is not taken.) Reference: ANSI Sec. 3.3.2.2 . 32. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (note particularly that an apostrophe within a contracted word could look like the beginning of a character constant), and no newlines inside quotes. Therefore, natural-language comments and pseudocode should always be written between the "official" comment delimiters /* and */. (But see also question 91.) References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37. 33. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which are neither under the control of the ANSI standard nor the C compiler developers on the systems which have them. The limitation is only that identifiers be _significant_ in the first six characters, not that they be restricted to six characters in length. This limitation is annoying, but certainly not unbearable, and is marked in the Standard as "obsolescent," i.e. a future revision will likely relax it. This concession to current, restrictive linkers really had to be made, no matter how vehemently some people oppose it. (The Rationale notes that its retention was "most painful.") If you disagree, or have thought of a trick by which a compiler burdened with a restrictive linker could present the C programmer with the appearance of more significance in external identifiers, read the excellently-worded section 3.1.2 in the X3.159 Rationale (see question 27), which discusses several such schemes and explains why they could not be mandated. References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale Sec. 3.1.2 pp. 19-21. 34. What was noalias and what ever happened to it? A: noalias was another type qualifier, in the same syntactic class as const and volatile, which was intended to assert that the object pointed to was not also pointed to ("aliased") by other pointers. The primary application, which is an important one, would have been for the formal parameters of subroutines designed to perform computations on large arrays. A compiler cannot usually take advantage of vectorization or other parallelization hardware (on supercomputers which have it) unless it can ensure that the source and destination arrays do not overlap. The noalias keyword was not backed up by any "prior art," and it was introduced late in the review and approval process. It was phenomenally difficult to define precisely and explain coherently, and sparked widespread, acrimonious debate. It had far-ranging implications, particularly on several standard library interfaces, for which easy fixes were not readily apparent. Because of the criticism and the difficulty of defining noalias well, the Committee wisely declined to adopt it, in spite of its superficial attractions. (When writing a standard, features cannot be introduced halfway; their full integration, and all implications, must be understood.) The need for an explicit mechanism to support parallel implementation of non-overlapping operations remains unfilled (although the C Numerical Extensions Working Group is examining the problem). References: ANSI Sec. 3.9.6 . 35. What are #pragmas and what are they good for? A: The #pragma directive provides a single, well-defined "escape hatch" which can be used for all sorts of implementation-specific controls and extensions: source listing control, structure packing, warning suppression (like the old lint /* NOTREACHED */ comments), etc. References: ANSI Sec. 3.8.6 . Section 5. C Preprocessor 36. How can I write a generic macro to swap two values? A: There is no good answer to this question. If the values are integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers, (and it will not work if the two values are the same variable, and the "obvious" supercompressed implementation for integral types a^=b^=a^=b is, strictly speaking, illegal due to multiple side- effects, and...). If the macro is intended to be used on values of arbitrary type (the usual goal), it cannot use a temporary, since it does not know what type of temporary it needs, and standard C does not provide a typeof operator. The best all-around solution is probably to forget about using a macro, unless you don't mind passing in the type as a third argument. 37. I have some old code that tries to construct identifiers with a macro like #define Paste(a, b) a/**/b but it doesn't work any more. A: That comments disappeared entirely and could therefore be used for token pasting was an undocumented feature of some early preprocessor implementations, notably Reiser's. ANSI affirms (as did K&R) that comments are replaced with white space. However, since the need for pasting tokens was demonstrated and real, ANSI introduced a well-defined token-pasting operator, ##, which can be used like this: #define Paste(a, b) a##b Reference: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7. 38. What's the best way to write a multi-statement cpp macro? A: The usual goal is to write a macro that can be invoked as if it were a single function-call statement. This means that the "caller" will be supplying the final semicolon, so the macro body should not. The macro body cannot be a simple brace-delineated compound statement, because syntax errors would result if it were invoked (apparently as a single statement, but with a resultant extra semicolon) as the if branch of an if/else statement with an explicit else clause. The traditional solution is to use #define Func() do { \ /* declarations */ \ stmt1; \ stmt2; \ /* ... */ \ } while(0) /* (no trailing ; ) */ When the "caller" appends a semicolon, this expansion becomes a single statement regardless of context. (An optimizing compiler will remove any "dead" tests or branches on the constant condition 0, although lint may complain.) If all of the statements in the intended macro are simple expressions, with no declarations or loops, another technique is to write a single, parenthesized expression using one or more comma operators. (This technique also allows a value to be "returned.") Reference: CT&P Sec. 6.3 pp. 82-3. 39. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); The obvious disadvantage is that the caller must always remember to use the extra parentheses. (It is often best to use a bona-fide function, which can take a variable number of arguments in a well- defined way, rather than a macro. See questions 40 and 41 below.) Section 6. Variable-Length Argument Lists 40. How can I write a function that takes a variable number of arguments? A: Use the <stdarg.h> header (or, if you must, the older <varargs.h>). Here is a function which concatenates an arbitrary number of strings into malloc'ed memory: #include <stddef.h> /* for NULL, size_t */ #include <stdarg.h> /* for va_ stuff */ #include <string.h> /* for strcat et al */ #include <stdlib.h> /* for malloc */ char *vstrcat(char *first, ...) { size_t len = 0; char *retbuf; va_list argp; char *p; if(first == NULL) return NULL; len = strlen(first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) len += strlen(p); va_end(argp); retbuf = malloc(len + 1); /* +1 for trailing \0 */ if(retbuf == NULL) return NULL; /* error */ (void)strcpy(retbuf, first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) (void)strcat(retbuf, p); va_end(argp); return retbuf; } Usage is something like char *str = vstrcat("Hello, ", "world!", (char *)NULL); Note the cast on the last argument. (Also note that the caller must free the returned, malloc'ed storage.) Under a pre-ANSI compiler, rewrite the function definition without a prototype ("char *vstrcat(first) char *first; {"), include <stdio.h> rather than <stddef.h>, replace "#include <stdlib.h>" with "extern char *malloc();", and use int instead of size_t. You may also have to delete the (void) casts, and use the older varargs package instead of stdarg. See the next question for hints. References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 . 41. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. Here is an "error" routine which prints an error message, preceded by the string "error: " and terminated with a newline: #include <stdio.h> #include <stdarg.h> void error(char *fmt, ...) { va_list argp; fprintf(stderr, "error: "); va_start(argp, fmt); vfprintf(stderr, fmt, argp); va_end(argp); fprintf(stderr, "\n"); } To use the older <varargs.h> package, instead of <stdarg.h>, change the function header to: void error(va_alist) va_dcl { char *fmt; change the va_start line to va_start(argp); and add the line fmt = va_arg(argp, char *); between the calls to va_start and vfprintf. (Note that there is no semicolon after va_dcl.) References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 . 42. How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Some systems provide a nonstandard nargs() function, but its use is questionable, since it typically returns the number of words pushed, not the number of arguments. (Floating point values and structures are usually passed as several words.) Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. printf-like functions do this by looking for formatting specifiers (%d and the like) in the format string (which is why these functions fail badly if the format string does not match the argument list). Another common technique (useful when the arguments are all of the same type) is to use a sentinel value (often 0, -1, or an appropriately-cast null pointer) at the end of the list (see the execl and vstrcat examples under questions 2 and 40 above). Section 7. Lint 43. I just typed in this program, and it's acting strangely. Can you see anything wrong with it? A: Try running lint first. Many C compilers are really only half- compilers, electing not to diagnose numerous source code difficulties which would not actively preclude code generation. 44. How can I shut off the "warning: possible pointer alignment problem" message lint gives me for each call to malloc? A: The problem is that traditional versions of lint do not know, and cannot be told, that malloc "returns a pointer to space suitably aligned for storage of any type of object." It is possible to provide a pseudoimplementation of malloc, using a #define inside of #ifdef lint, which effectively shuts this warning off, but a simpleminded #definition will also suppress meaningful messages about truly incorrect invocations. It may be easier simply to ignore the message, perhaps in an automated way with grep -v. 45. Where can I get an ANSI-compatible lint? A: A product called FlexeLint is available (in "shrouded source form," for compilation on 'most any system) from Gimpel Software 3207 Hogarth Lane Collegeville, PA 19426 USA (+1) 215 584 4261 The System V release 4 lint is ANSI-compatible, and is available separately (bundled with other C tools) from Unix Support Labs (a subsidiary of AT&T), or from System V resellers. Section 8. Memory Allocation 46. Why doesn't this fragment work? char *answer; printf("Type something:\n"); gets(answer); printf("You typed \"%s\"\n", answer); A: The pointer variable "answer," which is handed to the gets function as the location into which the response should be stored, has not been set to point to any valid storage. That is, we cannot say where the pointer "answer" points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that "answer" starts out as a null pointer. See question 82.) The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation: #include <string.h> char answer[100], *p; printf("Type something:\n"); fgets(answer, 100, stdin); if((p = strchr(answer, '\n')) != NULL) *p = '\0'; printf("You typed \"%s\"\n", answer); Note that this example also uses fgets instead of gets (always a good idea), so that the size of the array can be specified, so that fgets will not overwrite the end of the array if the user types an overly-long line. (Unfortunately for this example, fgets does not automatically delete the trailing \n, as gets would.) It would also be possible to use malloc to allocate the answer buffer, and/or to parameterize its size (#define ANSWERSIZE 100). 47. I can't get strcat to work. I tried char *s1 = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. C does not provide an automatically-managed string type. C compilers only allocate memory for objects explicitly mentioned in the source code (in the case of "strings," this includes character arrays and string literals). The programmer must arrange (explicitly) for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or by calling malloc. strcat performs no allocation; the second string is appended to the first one, in place. Therefore, one fix would be to declare the first string as an array with sufficient space: char s1[20] = "Hello, "; Since strcat returns the value of its first argument (s1, in this case), the s3 variable is superfluous. Reference: CT&P Sec. 3.2 p. 32. 48. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. If a library routine's documentation does not explicitly mention allocation, it is usually the caller's problem. The Synopsis section at the top of a Unix-style man page can be misleading. The code fragments presented there are closer to the function definition used by the call's implementor than the invocation used by the caller. In particular, many routines which accept pointers (e.g. to structs or strings), are usually called with the address of some object (a struct, or an array -- see questions 18 and 19.) Another common example is stat(). 49. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages for malloc stated that the contents of freed memory was "left undisturbed;" this ill-advised guarantee was never universal and is not required by ANSI. Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list: struct list *listp, *nextp; for(listp = base; listp != NULL; listp = nextp) { nextp = listp->next; free((char *)listp); } and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer. References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10 p. 95. 50. How does free() know how many bytes to free? A: The malloc/free package remembers the size of each block it allocates and returns, so it is not necessary to remind it of the size when freeing. 51. Is it legal to pass a null pointer as the first argument to realloc()? Why would you want to? A: ANSI C sanctions this usage (and the related realloc(..., 0), which frees), but several earlier implementations do not support it, so it is not widely portable. Passing an initially-null pointer to realloc can make it easier to write a self-starting incremental allocation algorithm. References: ANSI Sec. 4.10.3.4 . 52. What is the difference between calloc and malloc? Is it safe to use calloc's zero-fill guarantee for pointer and floating-point values? Does free work on memory allocated with calloc, or do you need a cfree? A: calloc(m, n) is essentially equivalent to p = malloc(m * n); memset(p, 0, m * n); The zero fill is all-bits-zero, and does not therefore guarantee useful zero values for pointers (see questions 1-14) or floating- point values. free can (and should) be used to free the memory allocated by calloc. References: ANSI Secs. 4.10.3 to 4.10.3.2 . 53. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function which called alloca returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context. alloca cannot be written portably, and is difficult to implement on machines without a stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), 100, stdin). For these reasons, alloca cannot be used in programs which must be widely portable, no matter how useful it might be. Section 9. Structures 54. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: What K&R I said was that the restrictions on struct operations would be lifted in a forthcoming version of the compiler, and in fact struct assignment and passing were fully functional in Ritchie's compiler even as K&R I was being published. Although a few early C compilers lacked struct assignment, all modern compilers support it, and it is part of the ANSI C standard, so there should be no reluctance to use it. References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 . 55. How does struct passing and returning work? A: When structures are passed as arguments to functions, the entire struct is typically pushed on the stack, using as many words as are required. (Pointers to structures are often chosen precisely to avoid this overhead.) Structures are typically returned from functions in a location pointed to by an extra, compiler-supplied "hidden" argument to the function. Older compilers often used a special, static location for structure returns, although this made struct-valued functions nonreentrant, which ANSI C disallows. Reference: ANSI Sec. 2.2.3 p. 13. 56. The following program works correctly, but it dumps core after it finishes. Why? struct list { char *item; struct list *next; } /* Here is the main program. */ main(argc, argv) ... A: A missing semicolon causes the compiler to believe that main returns a struct list. (The connection is hard to see because of the intervening comment.) Since struct-valued functions are usually implemented by adding a hidden return pointer, the generated code for main() actually expects three arguments, although only two were passed (in this case, by the C start-up code). See also question 96. Reference: CT&P Sec. 2.3 pp. 21-2. 57. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. A byte- by-byte comparison could be invalidated by random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison would require unacceptable amounts of repetitive, in-line code for large structures. If you want to compare two structures, you must write your own function to do so. C++ would let you arrange for the == operator to map to your function. References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI Rationale Sec. 3.3.9 p. 47. 58. I came across some code that declared a structure like this: struct name { int namelen; char name[1]; }; and then did some tricky allocation to make the name array act like it had several elements. Is this legal and/or portable? A: This technique is popular, although Dennis Ritchie has called it "unwarranted chumminess with the compiler." The ANSI C standard allows it only implicitly. It seems to be portable to all known implementations. (Compilers which check array bounds carefully might issue warnings.) 59. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available; see <stddef.h>. If you don't have it, a suggested implementation is #define offsetof(type, mem) ((size_t) \ ((char *)&((type *) 0)->mem - (char *)((type *) 0))) This implementation is not 100% portable; some compilers may legitimately refuse to accept it. See the next question for a usage hint. Reference: ANSI Sec. 4.1.5 . 60. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is offsetb = offsetof(struct a, b) If structp is a pointer to an instance of this structure, and b is an int field with offset as computed above, b's value can be set indirectly with *(int *)((char *)structp + offsetb) = value; Section 10. Declarations 61. How do you decide which integer type to use? A: If you might need large values (above 32767 or below -32767), use long. If space is very important (there are large arrays or many structures), use short. Otherwise, use int. If well-defined overflow characteristics are important and/or negative values are not, use the corresponding unsigned types. (But beware mixtures of signed and unsigned.) Similar arguments apply when deciding between float and double. Exceptions apply if the address of a variable is taken and must have a particular type. Although char or unsigned char can be used as a "tiny" int type, doing so is often more trouble than it's worth. 62. I can't seem to define a linked list successfully. I tried typedef struct { char *item; NODEPTR next; } *NODEPTR; but the compiler gave me error messages. Can't a struct in C contain a pointer to itself? A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. The problem with this example is that the NODEPTR typedef is not complete when the "next" field is declared. You will have to give the structure a tag ("struct node"), and declare the "next" field as "struct node next;". A similar problem, with a similar solution, can arise when attempting to declare a pair of typedef'ed mutually recursive structures. References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 . 63. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: This question can be answered in at least three ways (all assume the hypothetical array is to have 5 elements): 1. char *(*(*a[5])())(); 2. Build the declaration up in stages, using typedefs: typedef char *pc; /* pointer to char */ typedef pc fpc(); /* function returning pointer to char */ typedef fpc *pfpc; /* pointer to above */ typedef pfpc fpfpc(); /* function returning... */ typedef fpfpc *pfpfpc; /* pointer to... */ pfpfpc a[5]; /* array of... */ 3. Use the cdecl program, which turns English into C and vice versa: cdecl> declare a as array 5 of pointer to function returning pointer to function returning pointer to char char *(*(*a[5])())() cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions, like the above). Any good book on C should explain how to read these complicated C declarations "inside out" to understand them ("declaration mimics use"). Reference: H&S Sec. 5.10.1 p. 116. 64. So where can I get cdecl? A: Several public-domain versions are available. One is in volume 14 of comp.sources.unix . (See question 89.) Reference: K&R II Sec. 5.12 . 65. I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one? A: Use something like extern int func(); int (*fp)() = func; When the name of a function appears in an expression but is not being called (i.e. is not followed by a "("), it "decays" into a pointer (i.e. it has its address implicitly taken), much as an array name does. An explicit extern declaration for the function is normally needed, since implicit external function declaration does not happen in this case (again, because the function name is not followed by a "("). 66. I've seen different methods used for calling through pointers to functions. What's the story? A: Originally, a pointer to a function had to be "turned into" a "real" function, with the * operator (and an extra pair of parentheses, to keep the precedence straight), before calling: int r, f(), (*fp)() = f; r = (*fp)(); Another analysis holds that functions are always called through pointers, but that "real" functions decay implicitly into pointers (in expressions, as they do in initializations) and so cause no trouble. This reasoning, which was adopted in the ANSI standard, means that r = fp(); is legal and works correctly, whether fp is a function or a pointer to one. (The usage has always been unambiguous; there is nothing you ever could have done with a function pointer followed by an argument list except call through it.) An explicit * is harmless, and still allowed (and recommended, if portability to older compilers is important). References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41. Section 11. Boolean Expressions and Variables 67. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. (Using an int for a boolean may be faster, while using char may save data space.) The choice between #defines and enums is arbitrary and not terribly interesting. Use any of #define TRUE 1 #define YES 1 #define FALSE 0 #define NO 0 enum bool {false, true}; enum bool {no, yes}; or use raw 1 and 0, as long as you are consistent within one program or project. (An enum may be preferable if your debugger expands enum values when examining variables.) Some people prefer variants like #define TRUE (1==1) #define FALSE (!TRUE) or define "helper" macros such as #define Istrue(e) ((e) != 0) These don't buy anything (see below). 68. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test if((a == b) == TRUE) will work as expected (as long as TRUE is 1), but it is obviously silly. In general, explicit tests against TRUE and FALSE are undesirable, because some library functions (notably isupper, isalpha, etc.) return, on success, a nonzero value which is _not_ necessarily 1. (Besides, if you believe that "if((a == b) == TRUE)" is an improvement over "if(a == b)", why stop there? Why not use "if(((a == b) == TRUE) == TRUE)"?) A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable, or as the return value from a Boolean function, never in a comparison. The preprocessor macros TRUE and FALSE (and, of course, NULL) are used for code readability, not because the underlying values might ever change. That "true" is 1 and "false" 0 is guaranteed by the language. (See also question 7.) References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5; Achilles and the Tortoise. 69. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. Although many people might have wished otherwise, the ANSI standard says that enumerations may be freely intermixed with integral types, without errors. (If such intermixing were disallowed without explicit casts, judicious use of enums could catch certain programming errors.) The primary advantages of enums are that the numeric values are automatically assigned, and that a debugger may be able to display the symbolic values when enum variables are examined. (A compiler may also generate nonfatal warnings when enums and ints are indiscriminately mixed, since doing so can still be considered bad style even though it is not strictly illegal). A disadvantage is that the programmer has little control over the size (or over those nonfatal warnings). References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 . Section 12. Operating System Dependencies 70. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. The delivery of characters from a "keyboard" to a C program is a function of the operating system in use, and cannot be standardized by the C language. Some versions of curses have a cbreak() function which does what you want. Under UNIX, use ioctl to play with the terminal driver modes (CBREAK or RAW under "classic" versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or Posix systems). Under MS-DOS, use getch(). Under other operating systems, you're on your own. Beware that some operating systems make this sort of thing impossible, because character collection into input lines is done by peripheral processors not under direct control of the CPU running your program. Operating system specific questions are not appropriate for comp.lang.c . Many common questions are answered in frequently- asked questions postings in such groups as comp.unix.questions and comp.sys.ibm.pc.misc . Note that the answers are often not unique even across different variants of a system. Bear in mind when answering system-specific questions that the answer that applies to your system may not apply to everyone else's. References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1. 71. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. Some versions of curses have a nodelay() function. Depending on your system, you may also be able to use "nonblocking I/O", or a system call named "select", or the FIONREAD ioctl, or kbhit(), or rdchk(), or the O_NDELAY option to open() or fcntl(). 72. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname, or it may contain nothing. You may be able to duplicate the command language interpreter's search path logic to locate the executable if the name in argv[0] is present but incomplete. However, there is no guaranteed or portable solution. 73. How can a process change an environment variable in its caller? A: In general, it cannot. Different operating systems implement name/value functionality similar to the Unix environment in different ways. Whether the "environment" can be usefully altered by a running program, and if so, how, is system-dependent. Under Unix, a process can modify its own environment (some systems provide setenv() and/or putenv() functions to do this), and the modified environment is usually passed on to any child processes, but it is _not_ propagated back to the parent process. 74. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and several others supply chsize(), but there is no truly portable solution. Section 13. Stdio 75. Why does errno contain ENOTTY after a call to printf? A: Many implementations of the stdio package adjust their behavior slightly if stdout is a terminal. To make the determination, these implementations perform an operation which fails (with ENOTTY) if stdout is not a terminal. Although the output operation goes on to complete successfully, errno still contains ENOTTY. Reference: CT&P Sec. 5.4 p. 73. 76. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) whenever output should definitely be visible. Several mechanisms attempt to perform the fflush for you, at the "right time," but they tend to apply only when stdout is a terminal. (See question 75.) 77. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. In particular, "\n" in a format string does not mean "expect a newline", it means "discard all whitespace". It is usually better to fgets() to read a whole line, and then use sscanf() or other string functions to parse the line buffer. 78. How can I recover the file name given an open file descriptor? A: This problem is, in general, insoluble. Under Unix, for instance, a scan of the entire disk, (perhaps requiring special permissions) would theoretically be required, and would fail if the file descriptor was a pipe or referred to a deleted file (and could give a misleading answer for a file with multiple links). It is best to remember the names of open files yourself (perhaps with a wrapper function around fopen). Section 14. Style 79. Here's a neat trick: if(!strcmp(s1, s2)) Is this good style? A: No. This is a classic example of C minimalism carried to an obnoxious degree. The test succeeds if the two strings are equal, but its form strongly suggests that it tests for inequality. A much better solution is to use a macro: #define Streq(s1, s2) (strcmp(s1, s2) == 0) 80. What's the best style for code layout in C? A: K&R, while providing the example most often copied, also supply a good excuse for avoiding it: The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently. It is more important that the layout chosen be consistent (with itself, and with nearby or common code) than that it be "perfect." If your coding environment (i.e. local custom or company policy) does not suggest a style, and you don't feel like inventing your own, just copy K&R. (The tradeoffs between various indenting and brace placement options can be exhaustively and minutely examined, but don't warrant repetition here. See also the Indian Hill Style Guide.) Reference: K&R Sec. 1.2 p. 10. 81. Where can I get the "Indian Hill Style Guide" and other coding standards? A: Various documents are available for anonymous ftp from: Site: File or directory: cs.washington.edu ~ftp/pub/cstyle.tar.Z (128.95.1.4) (the updated Indian Hill guide) cs.toronto.edu doc/programming giza.cis.ohio-state.edu pub/style-guide Section 15. Miscellaneous 82. What can I safely assume about the initial values of variables which are not explicitly initialized? If global variables start out as "zero," is that good enough for null pointers and floating- point zeroes? A: Variables with "static" duration (that is, those declared outside of functions, and those declared with the storage class static), are guaranteed initialized to zero, as if the programmer had typed "= 0". Therefore, such variables are initialized to the null pointer (of the correct type) if they are pointers, and to 0.0 if they are floating-point. Variables with "automatic" duration (i.e. local variables without the static storage class) start out containing garbage, unless they are explicitly initialized. Nothing useful can be predicted about the garbage. Dynamically-allocated memory obtained with malloc and realloc is also likely to contain garbage, and must be initialized by the calling program, as appropriate. Memory obtained with calloc contains all-bits-0, but this is not necessarily useful for pointer or floating-point values (see question 52). 83. Can someone tell me how to write itoa (the inverse of atoi)? A: Just use sprintf. (You'll have to allocate space for the result somewhere anyway; see questions 46 and 47. Don't worry that sprintf may be overkill, potentially wasting run time or code space; it works well in practice.) References: K&R I Sec. 3.6 p. 60; K&R II Sec. 3.6 p. 64. 84. I know that the library routine localtime will convert a time_t into a broken-down struct tm, and that ctime will convert a time_t to a printable string. How can I perform the inverse operations of converting a struct tm or a string into a time_t? A: ANSI C specifies a library routine, mktime, which converts a struct tm to a time_t. Several public-domain versions of this routine are available in case your compiler does not support it yet. Converting a string to a time_t is harder, because of the wide variety of date and time formats which should be parsed. Public- domain routines have been written for performing this function (see, for example, the file partime.c, widely distributed with the RCS package), but they are less likely to become standardized. References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI Sec. 4.12.2.3 . 85. How can I write data files which can be read on other machines with different word size, byte order, or floating point formats? A: The best solution is to use text files (usually ASCII), written with fprintf and read with fscanf or the like. (Similar advice also applies to network protocols.) Be skeptical of arguments which imply that text files are too big, or that reading and writing them is too slow. Not only is their efficiency frequently acceptable in practice, but the advantages of being able to manipulate them with standard tools can be overwhelming. If you must use a binary format, you can improve portability, and perhaps take advantage of prewritten I/O libraries, by making use of standardized formats such as Sun's XDR, OSI's ASN.1, or CCITT's X.409 . 86. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: Standard headers exist in part so that definitions appropriate to your compiler, operating system, and processor can be supplied. You cannot just pick up a copy of someone else's header file and expect it to work, unless that person is using exactly the same environment. Ask your compiler vendor why the file was not provided (or to send a replacement copy). 87. How can I call Fortran (BASIC, Pascal, ADA, lisp) functions from C? (And vice versa?) A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use, and may not be possible at all. Read your compiler documentation very carefully; sometimes there is a "mixed-language programming guide," although the techniques for passing arguments and ensuring correct run-time startup are often arcane. 88. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available: p2c written by Dave Gillespie, and posted to comp.sources.unix in March, 1990 (Volume 21). ptoc another comp.sources.unix contribution, this one written in Pascal (comp.sources.unix, Volume 10, also patches in Volume 13?). f2c jointly developed by people from Bell Labs, Bellcore, and Carnegie Mellon. To find about f2c, send the mail message "send index from f2c" to netlib@research.att.com or research!netlib. (It is also available via anonymous ftp on research.att.com, in directory dist/f2c.) A PL/M to C converter was posted to alt.sources in April, 1991. The following companies sell various translation tools and services: Cobalt Blue 2940 Union Ave., Suite C San Jose, CA 95124 USA (+1) 408 723 0474 Promula Development Corp. 3620 N. High St., Suite 301 Columbus, OH 43214 USA (+1) 614 263 5454 Micro-Processor Services Inc 92 Stone Hurst Lane Dix Hills, NY 11746 USA (+1) 519 499 4461 See also question 29. 89. Where can I get copies of all these public-domain programs? A: If you have access to Usenet, see the regular postings in the comp.sources.unix and comp.sources.misc newsgroups, which describe, in some detail, the archiving policies and how to retrieve copies. The usual approach is to use anonymous ftp and/or uucp from a central, public-spirited site, such as uunet.uu.net (192.48.96.2). However, this article cannot track or list all of the available archive sites and how to access them. The comp.archives newsgroup contains numerous announcements of anonymous ftp availability of various items. The "archie" mailserver can tell you which anonymous ftp sites have which packages; send the mail message "help" to archie@quiche.cs.mcgill.ca for information. 90. When will the next International Obfuscated C Contest (IOCCC) be held? How can I get a copy of the current and previous winning entries? A: The contest typically runs from early March through mid-May. To obtain a current copy of the rules, send email to: {pacbell,uunet,utzoo}!hoptoad!judges or judges@toad.com Contest winners are first announced at the Summer Usenix Conference in mid-June, and posted to the net in July. Previous winners are available on uunet (see question 89) under the directory ~/pub/ioccc. 91. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good, mostly because of the possibility of accidentally leaving comments unclosed by including the characters "/*" within them. For this reason, it is usually better to "comment out" large sections of code, which might contain comments, with #ifdef or #if 0 (but see question 32). The character sequences /* and */ are not special within double- quoted strings, and do not therefore introduce comments, because a program (particularly one which is generating C code as output) might want to print them. Reference: ANSI Rationale Sec. 3.1.9 p. 33. 92. How can I make this code more efficient? A: Efficiency, though a favorite comp.lang.c topic, is not important nearly as often as people tend to think it is. Most of the code in most programs is not time-critical. When code is not time- critical, it is far more important that it be written clearly and portably than that it be written maximally efficiently. (Remember that computers are very, very fast, and that even "inefficient" code can run without apparent delay.) It is notoriously difficult to predict what the "hot spots" in a program will be. When efficiency is a concern, it is important to use profiling software to determine which parts of the program deserve attention. Often, actual computation time is swamped by peripheral tasks such as I/O and memory allocation, which can be sped up by using buffering and cacheing techniques. For the small fraction of code that is time-critical, it is vital to pick a good algorithm; it is less important to "microoptimize" the coding details. Many of the "efficient coding tricks" which are frequently suggested (e.g. substituting shift operators for multiplication by powers of two) are performed automatically by even simpleminded compilers. Heavyhanded "optimization" attempts can make code so bulky that performance is degraded. For more discussion of efficiency tradeoffs, as well as good advice on how to increase efficiency when it is important, see chapter 7 of Kernighan and Plaugher's The Elements of Programming Style, and Jon Bentley's Writing Efficient Programs. 93. Are pointers really faster than arrays? Do function calls really slow things down? Is ++i faster than i = i + 1? A: Precise answers to these and many similar questions depend of course on the processor and compiler in use. If you simply must know, you'll have to time test programs carefully. (Often the differences are so slight that hundreds of thousands of iterations are required even to see them. Check the compiler's assembly language output, if available, to see if two purported alternatives aren't compiled identically.) It is "usually" faster to march through large arrays with pointers rather than array subscripts, but for some processors the reverse is true. Function calls, though obviously incrementally slower than in-line code, contribute so much to modularity and code clarity that there is rarely good reason to avoid them. Before rearranging expressions such as i = i + 1, remember that you are dealing with a C compiler, not a keystroke-programmable calculator. A good compiler will generate identical code for ++i, i += 1, and i = i + 1. The reasons for using ++i or i += 1 over i = i + 1 have to do with style, not efficiency. 94. My floating-point calculations are acting strangely and giving me different answers on different machines. A: Most digital computers use floating-point formats which provide a close but by no means exact simulation of real number arithmetic. Among other things, the associative and distributive laws do not hold completely (i.e. order of operation may be important, repeated addition is not necessarily equivalent to multiplication). Underflow or cumulative precision loss is often a problem. Don't assume that floating-point results will be exact, and especially don't assume that floating-point values can be compared for equality. (Don't throw haphazard "fuzz factors" in, either.) These problems are no worse for C than they are for any other computer language. Floating-point semantics are usually defined as "however the processor does them;" otherwise a compiler for a machine without the "right" model would have to do prohibitively expensive emulations. This article cannot begin to list the pitfalls associated with, and workarounds appropriate for, floating-point work. A good programming text should cover the basics. Do make sure that you have #included <math.h>, and correctly declared other functions returning double. References: K&P Sec. 6 pp. 115-8. 95. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C (and Ritchie's original PDP-11 compiler), leave out floating point support if it looks like it will not be needed. In particular, the non- floating-point versions of printf and scanf save space by not including code to handle %e, %f, and %g. It happens that Turbo C's heuristics for determining whether the program uses floating point are occasionally insufficient, and the programmer must sometimes insert a dummy explicit floating-point call to force loading of floating-point support. In general, questions about a particular compiler are inappropriate for comp.lang.c . Problems with PC compilers, for instance, will find a more receptive audience in a PC newsgroup (e.g. comp.os.msdos.programmer). 96. This program crashes before it even runs! (When single-stepping with a debugger, it dies before the first statement in main.) A: You probably have one or more very large (kilobyte or more) local arrays. Many systems have fixed-size stacks, and those which perform dynamic stack allocation automatically (e.g. Unix) can be confused when the stack tries to grow by a huge chunk all at once. It is often better to declare large arrays with static duration (unless of course you need a fresh set with each recursive call). (See also question 56.) 97. Does anyone have a C compiler test suite I can use? A: Plum Hall (1 Spruce Ave., Cardiff, NJ 08232, USA), among others, sells one. 98. Where can I get a YACC grammar for C? A: The definitive grammar is of course the one in the ANSI standard. Several copies are floating around; keep your eyes open. There is one on uunet.uu.net (192.48.96.2) in net.sources/ansi.c.grammar.Z . The FSF's GNU C compiler contains a grammar, as does the appendix to K&R II. References: ANSI Sec. A.2 . 99. How do you pronounce "char"? What's that funny name for the "#" character? A: You can pronounce the C keyword "char" like the English words "char," "care," or "car;" the choice is arbitrary. Bell Labs once proposed the (now obsolete) term "octothorpe" for the "#" character. Trivia questions like these aren't any more pertinent for comp.lang.c than they are for any of the other groups they frequently come up in. You can find lots of information in the net.announce.newusers frequently-asked questions postings, the "jargon file" (also published as _The Hacker's Dictionary_), and the Usenet ASCII pronunciation list. 100. Where can I get extra copies of this list? What about back issues? A: For now, just pull it off the net; it is normally posted to comp.lang.c on the first of each month, with an Expiration: line which should keep it around all month. Eventually, it may be available for anonymous ftp, or via a mailserver. This list is an evolving document, not just a collection of this month's interesting questions. Older copies are obsolete and don't contain much, except the occasional typo, that the current list doesn't. Bibliography ANSI American National Standard for Information Systems -- Programming Language -- C, ANSI X3.159-1989 (see question 28). Jon Louis Bentley, Writing Efficient Programs, Prentice-Hall, 1982, ISBN 0-13-970244-X. H&S Samuel P. Harbison and Guy L. Steele, C: A Reference Manual, Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0. (A third edition has recently been released.) PCS Mark R. Horton, Portable C Software, Prentice Hall, 1990, ISBN 0-13-868050-7. K&P Brian W. Kernighan and P.J. Plaugher, The Elements of Programming Style, Second Edition, McGraw-Hill, 1978, ISBN 0- 07-034207-5. K&R I Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall, 1978, ISBN 0-13-110163-3. K&R II Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Second Edition, Prentice Hall, 1988, ISBN 0-13- 110362-8, 0-13-110370-9. CT&P Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989, ISBN 0-201-17928-8. There is a more extensive bibliography in the revised Indian Hill style guide (see question 81). Acknowledgements Thanks to Sudheer Apte, Dan Bernstein, Joe Buehler, Raymond Chen, Christopher Calabrese, James Davies, Norm Diamond, Ray Dunn, Stephen M. Dunn, Bjorn Engsig, Ron Guilmette, Doug Gwyn, Tony Hansen, Joe Harrington, Guy Harris, Blair Houghton, Kirk Johnson, Andrew Koenig, John Lauro, Christopher Lott, Tim McDaniel, Evan Manning, Mark Moraes, Francois Pinard, randall@virginia, Pat Rankin, Rich Salz, Chip Salzenberg, Paul Sand, Doug Schmidt, Patricia Shanahan, Peter da Silva, Joshua Simons, Henry Spencer, Erik Talvola, Clarke Thatcher, Chris Torek, Ed Vielmetti, Larry Virden, Freek Wiedijk, and Dave Wolverton, who have contributed, directly or indirectly, to this article. Special thanks to Karl Heuer, and particularly to Mark Brader, who (to borrow a line from Steve Johnson) have goaded me beyond my inclination, and frequently beyond my endurance, in relentless pursuit of a better FAQ list. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990, 1991 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained. The C code in this article (vstrcat, error, etc.) is public domain and may be used without restriction.
scs@adam.mit.edu (Steve Summit) (05/01/91)
[Last modified April 29, 1991 by scs.] This article contains minimal answers to the comp.lang.c frequently- asked questions list. Please see the long version for more detailed explanations and references. Section 1. Null Pointers 1. What is this infamous null pointer, anyway? A: For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object. 2. How do I "get" a null pointer in my programs? A: A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable or expression of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic function calls) a constant 0 with an appropriate explicit cast is required. 3. What is NULL and how is it #defined? A: NULL is simply a preprocessor macro, #defined as 0 (or (void *)0), which is used (as a stylistic convention, in favor of unadorned 0's) to generate null pointers, 4. How should NULL be #defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? A: The same as any other machine: as 0 (or (void *)0). (The compiler makes the translation, upon seeing a 0, not the preprocessor.) 5. If NULL were defined as "(char *)0," wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. 6. I use the preprocessor macro "#define Nullptr(type) (type *)0" to help me build null pointers of the correct type. A: This trick, though valid, does not buy much. 7. Is the abbreviated pointer comparison "if(p)" to test for non-null pointers valid? What if the internal representation for null pointers is nonzero? A: The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. 8. If "NULL" and "0" are equivalent, which should I use? A: Either; the distinction is entirely stylistic. 9. But wouldn't it be better to use NULL (rather than 0) in case the value of NULL changes, perhaps on a machine with nonzero null pointers? A: No. NULL is, and will always be, 0. 10. I'm confused. NULL is guaranteed to be 0, but the null pointer is not? A: A "null pointer" is a language concept whose particular internal value does not matter. A null pointer is requested in source code with the character "0". "NULL" is a preprocessor macro, which is always #defined as 0 (or (void *)0). 11. Why is there so much confusion surrounding null pointers? Why do these questions come up so often? A: The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) suggests that the value might change later, or on some weird machine. 12. I'm still confused. I just can't understand all this null pointer stuff. A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." 13. Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? A: What would such a requirement really accomplish? 14. Seriously, have any actual machines really used nonzero null pointers? A: Machines manufactured by Prime and by Honeywell-Bull, as well as Symbolics Lisp Machines, have done so. Section 2. Arrays and Pointers 15. I had the definition char x[6] in one source file, and in another I declared extern char *x. Why didn't it work? A: The declaration extern char *x simply does not match the actual definition. Use extern char x[]. 16. But I heard that char x[] was identical to char *x. A: Not at all. Arrays are not pointers. 17. You mean that a reference like x[3] generates different code depending on whether x is an array or a pointer? A: Precisely. 18. So what is meant by the "equivalence of pointers and arrays" in C? A: An lvalue of type array-of-T which appears in an expression decays into a pointer to its first element; the type of the resultant pointer is pointer-to-T. 19. Why are array and pointer declarations interchangeable as function formal parameters? A: Since functions can never receive arrays as parameters, any parameter declarations which "look like" arrays are treated by the compiler as if they were pointers. 20. Someone explained to me that arrays were really just constant pointers. A: An array name is "constant" in that it cannot be assigned to, but an array is _not_ a pointer. 21. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? A: Yes, array subscripting is commutative in C. The array subscripting operation a[e] is defined as being equivalent to *((a)+(e)). 22. My compiler complained when I passed a two-dimensional array to a routine expecting a pointer to a pointer. A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. 23. How do I declare a pointer to an array? A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead. 24. How can I dynamically allocate a multidimensional array? A: It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. Section 3. Order of Evaluation 25. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++);" prints 49. Regardless of the order of evaluation, shouldn't it print 56? A: The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. 26. But what about the &&, ||, and comma operators? A: There is a special exception for those operators, (as well as ?: ); left-to-right evaluation is guaranteed. Section 4. ANSI C 27. What is the "ANSI C Standard?" A: In 1983, the American National Standards Institute commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, the committee's work was finally ratified as an American National Standard, X3.159-1989, on December 14, 1989, and published in the spring of 1990. The Standard has also been adopted as ISO/IEC 9899:1990. 28. How can I get a copy of the Standard? A: Copies are available from the American National Standards Institute in New York, or from Global Engineering Documents in Irvine, CA. See the unabridged list for addresses. 29. Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? A: See the full list for details. 30. What's the difference between "char const *p" and "char * const p"? A: The former is a pointer to a constant character; the latter is a constant pointer to a character. 31. My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; {... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". The problem can be fixed by using either new-style (prototype) or old-style syntax consistently. 32. I'm getting strange syntax errors inside code which I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no unterminated comments or quotes (i.e. no single apostrophes), and no newlines inside quotes. 33. Why does the ANSI Standard not guarantee more than six monocase characters of external identifier significance? A: The problem is older linkers which cannot be forced (by mere words in a Standard) to upgrade. 34. Whatever happened to noalias? A: It was deleted from the final versions of the standard because of widespread complaint and the near-impossibility of defining it properly. 35. What are #pragmas and what are they good for? A: The #pragma directive provides a single, well-defined "escape hatch" which can be used for extensions. Section 5. C Preprocessor 36. How can I write a generic macro to swap two values? A: There is no good answer to this question. The best all-around solution is probably to forget about using a macro. 37. I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b", but it doesn't work any more. A: Try the ANSI token-pasting operator ##. 38. What's the best way to write a multi-statement cpp macro? A: #define Func() do {stmt1; stmt2; ... } while(0) /* (no trailing ; ) */ 39. How can I write a cpp macro which takes a variable number of arguments? A: One popular trick is to define the macro with a single argument, and call it with a double set of parentheses, which appear to the preprocessor to indicate a single argument: #define DEBUG(args) {printf("DEBUG: "); printf args;} if(n != 0) DEBUG(("n is %d\n", n)); Section 6. Variable-Length Argument Lists 40. How can I write a function that takes a variable number of arguments? A: Use the <stdarg.h> header. 41. How can I write a function that takes a format string and a variable number of arguments, like printf, and passes them to printf to do most of the work? A: Use vprintf, vfprintf, or vsprintf. 42. How can I discover how many arguments a function was actually called with? A: Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. Section 7. Lint 43. I just typed in this program, and it's acting strangely. Can you see anything wrong with it? A: Try running lint first. 44. How can I shut off the "warning: possible pointer alignment problem" message lint gives me for each call to malloc? A: It may be easier simply to ignore the message, perhaps in an automated way with grep -v. 45. Where can I get an ANSI-compatible lint? A: See the unabridged list for two commercial products. Section 8. Memory Allocation 46. Why doesn't the code "char *answer; gets(answer);" work? A: The pointer variable "answer" has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. 47. I can't get strcat to work. I tried "char *s1 = "Hello, ", *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange results. A: Again, the problem is that space for the concatenated result is not properly allocated. 48. But the man page for strcat says that it takes two char *'s as arguments. How am I supposed to know to allocate things? A: In general, when using pointers you _always_ have to consider memory allocation, at least to make sure that the compiler is doing it for you. 49. You can't use dynamically-allocated memory after you free it, can you? A: No. Some early man pages implied otherwise, but the claim is no longer valid. 50. How does free() know how many bytes to free? A: The malloc/free package remembers the size of each block it allocates and returns. 51. Is it legal to pass a null pointer as the first argument to realloc()? A: ANSI C sanctions this usage, but several earlier implementations do not support it. 52. Is it safe to use calloc's zero-fill guarantee for pointer and floating-point values? A: calloc(m, n) is essentially equivalent to "p = malloc(m * n); memset(p, 0, m * n); ". The zero fill is all-bits-zero, and does not therefore guarantee useful zero values for pointers or floating-point values. 53. What is alloca and why is its use discouraged? A: alloca allocates memory which is automatically freed when the function which called alloca returns. alloca cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply. Section 9. Structures 54. I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not. A: These operations are supported by all modern compilers. 55. How does struct passing and returning work? A: If you really need to know, see the unabridged list. 56. I have a program which works correctly, but dumps core after it finishes. Why? A: Check to see if a structure type declaration just before main is missing its trailing semicolon, causing the compiler to believe that main returns a struct. See also question 96. 57. Why can't you compare structs? A: There is no reasonable way for a compiler to implement struct comparison which is consistent with C's low-level flavor. 58. I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make the array act like it had several elements. Is this legal and/or portable? A: The ANSI C standard allows it, but only implicitly. 59. How can I determine the byte offset of a field within a structure? A: ANSI C defines the offsetof macro, which should be used if available. 60. How can I access structure fields by name at run time? A: Build a table of names and offsets, using the offsetof() macro. Section 10. Declarations 61. How do you decide which integer type to use? A: If you might need large values, use long. If space is very important, use short. Otherwise, use int. 62. I can't seem to define a linked list node which contains a pointer to itself. A: Structs in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 63. How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? A: char *(*(*a[5])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. 64. So where can I get cdecl? A: Several public-domain versions are available. See the full list for details. 65. How do I initialize a pointer to a function? A: Use something like "extern int func(); int (*fp)() = func; " . 66. I've seen different methods used for calling through pointers to functions. A: The extra parentheses and explicit * are now officially optional, although some older implementations require them. Section 11. Boolean Expressions and Variables 67. What is the right type to use for boolean values in C? Why isn't it a standard type? Should #defines or enums be used for the true and false values? A: C does not provide a standard boolean type, because picking one involves a space/time tradeoff which is best decided by the programmer. The choice between #defines and enums is arbitrary and not terribly interesting. 68. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in boolean or relational operator "returns" something other than 1? A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a boolean value is expected. When a boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is _not_ true for some library routines such as isalpha.) 69. What is the difference between an enum and a series of preprocessor #defines? A: At the present time, there is little difference. The ANSI standard states that enumerations are compatible with integral types. Section 12. Operating System Dependencies 70. How can I read a single character from the keyboard without waiting for a newline? A: Contrary to popular belief and many people's wishes, this is not a C-related question. How to do so is a function of the operating system in use. 71. How can I find out if there are characters available for reading (and if so, how many)? Alternatively, how can I do a read that will not block if there are no characters available? A: These, too, are entirely operating-system-specific. 72. How can my program discover the complete pathname to the executable file from which it was invoked? A: argv[0] may contain all or part of the pathname. You may be able to duplicate the command language interpreter's search path logic to locate the executable. 73. How can a process change an environment variable in its caller? A: In general, it cannot. 74. How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), and several others supply chsize(), but there is no truly portable solution. Section 13. Stdio 75. Why does errno contain ENOTTY after a call to printf? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has occurred. 76. My program's prompts and intermediate output don't always show up on the screen, especially when I pipe the output through another program. A: It is best to use an explicit fflush(stdout) whenever output should definitely be visible. 77. When I read from the keyboard with scanf(), it seems to hang until I type one extra line of input. A: scanf() was designed for free-format input, which is seldom what you want when reading from the keyboard. 78. How can I recover the file name given an open file descriptor? A: This problem is, in general, insoluble. It is best to remember the names of open files yourself. Section 14. Style 79. Is the code "if(!strcmp(s1, s2))" good style? A: No. 80. What's the best style for code layout in C? A: There is no one "best style," but see the full list for a few suggestions. 81. Where can I get the "Indian Hill Style Guide" and other coding standards? A: See the unabridged list. Section 15. Miscellaneous 82. What can I safely assume about the initial values of variables which are not explicitly initialized? A: Variables with "static" duration start out as 0, as if the programmer had initialized them. Variables with "automatic" duration, and dynamically-allocated memory, start out containing garbage (with the exception of calloc). 83. Can someone tell me how to write itoa? A: Just use sprintf. 84. How can I convert a struct tm or a string into a time_t? A: The ANSI mktime routine converts a struct tm to a time_t. No standard routine exists to parse strings. 85. How can I write data files which can be read on other machines with different data formats? A: The best solution is to use text files. 86. I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: You cannot just pick up a copy of someone else's header file and expect it to work, since the definitions within header files are frequently system-dependent. Contact your vendor. 87. How can I call Fortran (BASIC, Pascal, ADA, lisp) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 88. Does anyone know of a program for converting Pascal (Fortran, lisp, "Old" C, ...) to C? A: Several public-domain programs are available, namely ptoc, p2c, and f2c. See the full list for details. 89. Where can I get copies of all these public-domain programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups for information. 90. When will the next Obfuscated C Contest be held? How can I get a copy of the previous winning entries? A: See the full list, or send email to judges@toad.com . 91. Why don't C comments nest? Are they legal inside quoted strings? A: Nested comments would cause more harm than good. The character sequences /* and */ are not special within double-quoted strings. 92. How can I make this code more efficient? A: Efficiency is not important nearly as often as people tend to think it is. Most of the time, by simply paying attention to good algorithm choices, perfectly acceptable results can be achieved. 93. Are pointers really faster than arrays? Do function calls really slow things down? A: Precise answers to these and many similar questions depend of course on the processor and compiler in use. 94. My floating-point calculations are acting strangely and giving me different answers on different machines. A: See the full list for a brief explanation, or any good programming book for a better one. 95. I'm having trouble with a Turbo C program which crashes and says something like "floating point not loaded." A: Some compilers for small machines, including Turbo C, attempt to leave out floating point support if it looks like it will not be needed. The programmer must occasionally insert a dummy explicit floating-point call to force loading of floating-point support. 96. This program crashes before it even runs! A: Look for very large, local arrays. (See also question 56.) 97. Does anyone have a C compiler test suite I can use? A: Plum Hall, among others, sells one. 98. Where can I get a YACC grammar for C? A: See the ANSI Standard, or the unabridged list. 99. How do you pronounce "char"? A: Like the English words "char," "care," or "car" (your choice). 100. Where can I get extra copies of this list? A: For now, just pull it off the net; the unabridged version is normally posted on the first of each month, with an Expiration: line which should keep it around all month. Steve Summit scs@adam.mit.edu scs%adam.mit.edu@mit.edu mit-eddie!adam!scs This article is Copyright 1988, 1990, 1991 by Steve Summit. It may be freely redistributed so long as the author's name, and this notice, are retained.