iefly: implementation-defined means that an implementation must choose some behavior and document it. Unspecified means that an implementation should choose some behavior, but need not document it. Undefined means that absolutely anything might happen. In no case does the Standard impose requirements; in the first two cases it occasionally suggests (and may require a choice from among) a small set of likely behaviors. Note that since the Standard imposes *no* requirements on the behavior of a compiler faced with an instance of undefined behavior, the compiler can do absolutely anything. In particular, there is no guarantee that the rest of the program will perform normally. It's perilous to think that you can tolerate undefined behavior in a program; see question 3.2 for a relatively simple example. If you're interested in writing portable code, you can ignore the distinctions, as you'll want to avoid code that depends on any of the three behaviors. See also questions 3.9, and 11.34. References: ISO Sec. 3.10, Sec. 3.16, Sec. 3.17; Rationale Sec. 1.6. 11.34: I'm appalled that the ANSI Standard leaves so many issues undefined. Isn't a Standard's whole job to standardize these things? A: It has always been a characteristic of C that certain constructs behaved in whatever way a particular compiler or a particular piece of hardware chose to implement them. This deliberate imprecision often allows compilers to generate more efficient code for common cases, without having to burden all programs with extra code to assure well-defined behavior of cases deemed to be less reasonable. Therefore, the Standard is simply codifying existing practice. A programming language standard can be thought of as a treaty between the language user and the compiler implementor. Parts of that treaty consist of features which the compiler implementor agrees to provide, and which the user may assume will be available. Other parts, however, consist of rules which the user agrees to follow and which the implementor may assume will be followed. As long as both sides uphold their guarantees, programs have a fighting chance of working correctly. If *either* side reneges on any of its commitments, nothing is guaranteed to work. See also question 11.35. References: Rationale Sec. 1.1. 11.35: People keep saying that the behavior of i = i++ is undefined, but I just tried it on an ANSI-conforming compiler, and got the results I expected. A: A compiler may do anything it likes when faced with undefined behavior (and, within limits, with implementation-defined and unspecified behavior), including doing what you expect. It's unwise to depend on it, though. See also questions 11.32, 11.33, and 11.34. Section 12. Stdio 12.1: What's wrong with this code? char c; while((c = getchar()) != EOF) ... A: For one thing, the variable to hold getchar's return value must be an int. getchar() can return all possible character values, as well as EOF. By squeezing getchar's return value into a char, either a normal character might be misinterpreted as EOF, or the EOF might be altered (particularly if type char is unsigned) and so never seen. References: K&R1 Sec. 1.5 p. 14; K&R2 Sec. 1.5.1 p. 16; ISO Sec. <IP_ADDRESS>, Sec. 7.9.1, Sec. <IP_ADDRESS>; H&S Sec. 5.1.3 p. 116, Sec. 15.1, Sec. 15.6; CT&P Sec. 5.1 p. 70; PCS Sec. 11 p. 157. 12.2: Why does the code while(!feof(infp)) { fgets(buf, MAXLINE, infp); fputs(buf, outfp); } copy the last line twice? A: In C, end-of-file is only indicated *after* an input routine has tried to read, and failed. (In other words, C's I/O is not like Pascal's.) Usually, you should just check the return value of the input routine (in this case, fgets() will return NULL on end- of-file); often, you don't need to use feof() at all. References: K&R2 Sec. 7.6 p. 164; ISO Sec. 7.9.3, Sec. <IP_ADDRESS>, Sec. <IP_ADDRESS>; H&S Sec. 15.14 p. 382. 12.4: 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's best to use an explicit fflush(stdout) whenever output should definitely be visible (and especially if the text does not end with \n). Several mechanisms attempt to perform the fflush() for you, at the "right time," but they tend to apply only when stdout is an interactive terminal. (See also question 12.24.) References: ISO Sec. <IP_ADDRESS>. 12.5: How can I read one character at a time, without waiting for the RETURN key? A: See question 19.1. 12.6: How can I print a '%' character in a printf format string? I tried \%, but it didn't work. A: Simply double the percent sign: %% . \% can't work, because the backslash \ is the *compiler's* escape character, while here our problem is that the % is essentially printf's escape character. See also question 19.17. References: K&R1 Sec. 7.3 p. 147; K&R2 Sec. 7.2 p. 154; ISO Sec. <IP_ADDRESS>. 12.9: Someone told me it was wrong to use %lf with printf(). How can printf() use %f for type double, if scanf() requires %lf? A: It's true that printf's %f specifier works with both float and double arguments. Due to the "default argument promotions" (which apply in variable-length argument lists such as printf's, whether or not prototypes are in scope), values of type float are promoted to double, and printf() therefore sees only doubles. (printf() does accept %Lf, for long double.) See also questions 12.13 and 15.2. References: K&R1 Sec. 7.3 pp. 145-47, Sec. 7.4 pp. 147-50; K&R2 Sec. 7.2 pp. 153-44, Sec. 7.4 pp. 157-59; ISO Sec. <IP_ADDRESS>, Sec. <IP_ADDRESS>; H&S Sec. 15.8 pp. 357-64, Sec. 15.11 pp. 366-78; CT&P Sec. A.1 pp. 121-33. 12.9b: What printf format should I use for a typedef like size_t when I don't know whether it's long or some other type? A: Use a cast to convert the value to a known, conservatively- sized type, then use the printf format matching that type. For example, to print the size of a type, you might use printf("%lu", (unsigned long)sizeof(thetype)); 12.10: How can I implement a variable field width with printf? That is, instead of %8d, I want the width to be specified at run time. A: printf("%*d", width, x) will do just what you want. See also question 12.15. References: K&R1 Sec. 7.3; K&R2 Sec. 7.2; ISO Sec. <IP_ADDRESS>; H&S Sec. 15.11.6; CT&P Sec. A.1. 12.11: How can I print numbers with commas separating the thousands? What about currency formatted numbers? A: The functions in <locale.h> begin to provide some support for these operations, but there is no standard routine for doing either task. (The only thing printf() does in response to a custom locale setting is to change its decimal-point character.) References: ISO Sec. 7.4; H&S Sec. 11.6 pp. 301-4. 12.12: Why doesn't the call scanf("%d", i) work? A: The arguments you pass to scanf() must always be pointers. To fix the fragment above, change it to scanf("%d", &i) . 12.13: Why doesn't this code: double d; scanf("%f", &d); work? A: Unlike printf(), scanf() uses %lf for values of type double, and %f for float. See also question 12.9. 12.15: How can I specify a variable width in a scanf() format string? A: You can't; an asterisk in a scanf() format string means to suppress assignment. You may be able to use ANSI stringizing and string concatenation to accomplish about the same thing, or you can construct the scanf format string at run time. 12.17: When I read numbers from the keyboard with scanf "%d\n", it seems to hang until I type one extra line of input. A: Perhaps surprisingly, \n in a scanf format string does *not* mean to expect a newline, but rather to read and discard characters as long as each is a whitespace character. See also question 12.20. References: K&R2 Sec. B1.3 pp. 245-6; ISO Sec. <IP_ADDRESS>; H&S Sec. 15.8 pp. 357-64. 12.18: I'm reading a number with scanf %d and then a string with gets(), but the compiler seems to be skipping the call to gets()! A: scanf %d won't consume a trailing newline. If the input number is immediately followed by a newline, that newline will immediately satisfy the gets(). As a general rule, you shouldn't try to interlace calls to scanf() with calls to gets() (or any other input routines); scanf's peculiar treatment of newlines almost always leads to trouble. Either use scanf() to read everything or nothing. See also questions 12.20 and 12.23. References: ISO Sec. <IP_ADDRESS>; H&S Sec. 15.8 pp. 357-64. 12.19: I figured I could use scanf() more safely if I checked its return value to make sure that the user typed the numeric values I expect, but sometimes it seems to go into an infinite loop. A: When scanf() is attempting to convert numbers, any non-numeric characters it encounters terminate the conversion *and are left on the input stream*. Therefore, unless some other steps are taken, unexpected non-numeric input "jams" scanf() again and again: scanf() never gets past the bad character(s) to encounter later, valid data. If the user types a character like `x' in response to a numeric scanf format such as %d or %f, code that simply re-prompts and retries the same scanf() call will immediately reencounter the same `x'. See also question 12.20. References: ISO Sec. <IP_ADDRESS>; H&S Sec. 15.8 pp. 357-64. 12.20: Why does everyone say not to use scanf()? What should I use instead? A: scanf() has a number of problems -- see questions 12.17, 12.18, and 12.19. Also, its %s format has the same problem that gets() has (see question 12.23) -- it's hard to guarantee that the receiving buffer won't overflow. More generally, scanf() is designed for relatively structured, formatted input (its name is in fact derived from "scan formatted"). If you pay attention, it will tell you whether it succeeded or failed, but it can tell you only approximately where it failed, and not at all how or why. It's nearly impossible to do decent error recovery with scanf(); usually it's far easier to read entire lines (with fgets() or the like), then interpret them, either using sscanf() or some other techniques. (Functions like strtol(), strtok(), and atoi() are often useful; see also question 13.6.) If you do use any scanf variant, be sure to check the return value to make sure that the expected number of items were found. Also, if you use %s, be sure to guard against buffer overflow. References: K&R2 Sec. 7.4 p. 159. 12.21: How can I tell how much destination buffer space I'll need for an arbitrary sprintf call? How can I avoid overflowing the destination buffer with sprintf()? A: When the format string being used with sprintf() is known and relatively simple, you can sometimes predict a buffer size in an ad-hoc way. If the format consists of one or two %s's, you can count the fixed characters in the format string yourself (or let sizeof count them for you) and add in the result of calling strlen() on the string(s) to be inserted. For integers, the number of characters produced by %d is no more than ((sizeof(int) * CHAR_BIT + 2) / 3 + 1) /* +1 for '-' */ (CHAR_BIT is in <limits.h>), though this computation may be over- conservative. (It computes the number of characters required for a base-8 representation of a number; a base-10 expansion is guaranteed to take as much room or less.) When the format string is more complicated, or is not even known until run time, predicting the buffer size becomes as difficult as reimplementing sprintf(), and correspondingly error-prone (and inadvisable). A last-ditch technique which is sometimes suggested is to use fprintf() to print the same text to a bit bucket or temporary file, and then to look at fprintf's return value or the size of the file (but see question 19.12, and worry about write errors). If there's any chance that the buffer might not be big enough, you won't want to call sprintf() without some guarantee that the buffer will not overflow and overwrite some other part of memory. If the format string is known, you can limit %s expansion by using %.Ns for some N, or %.*s (see also question 12.10). The "obvious" solution to the overflow problem is a length- limited version of sprintf(), namely snprintf(). It would be used like this: snprintf(buf, bufsize, "You typed \"%s\"", answer); snprintf() has been available in several stdio libraries (including GNU and 4.4bsd) for several years. It will be standardized in C9X. When the C9X snprintf() arrives, it will also be possible to use it to predict the size required for an arbitrary sprintf() call. C9X snprintf() will return the number of characters it would have placed in the buffer, not just how many it did place. Furthermore, it may be called with a buffer size of 0 and a null pointer as the destination buffer. Therefore, the call nch = snprintf(NULL, 0, fmtstring, /* other arguments */ ); will compute the number of characters required for the fully- formatted string. References: C9X Sec. <IP_ADDRESS>. 12.23: Why does everyone say not to use gets()? A: Unlike fgets(), gets() cannot be told the size of the buffer it's to read into, so it cannot be prevented from overflowing that buffer. As a general rule, always use fgets(). See question 7.1 for a code fragment illustrating the replacement of gets() with fgets(). References: Rationale Sec. <IP_ADDRESS>; H&S Sec. 15.7 p. 356. 12.24: 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 some operation which happens to fail (with ENOTTY) if stdout is not a terminal. Although the output operation goes on to complete successfully, errno still contains ENOTTY. (Note that it is only meaningful for a program to inspect the contents of errno after an error has been reported; errno is not guaranteed to be 0 otherwise.) References: ISO Sec. 7.1.4, Sec. <IP_ADDRESS>; CT&P Sec. 5.4 p. 73; PCS Sec. 14 p. 254. 12.25: What's the difference between fgetpos/fsetpos and ftell/fseek? What are fgetpos() and fsetpos() good for? A: ftell() and fseek() use type long int to represent offsets (positions) in a file, and may therefore be limited to offsets of about 2 billion (2**31-1). The newer fgetpos() and fsetpos() functions, on the other hand, use a special typedef, fpos_t, to represent the offsets. The type behind this typedef, if chosen appropriately, can represent arbitrarily large offsets, so fgetpos() and fsetpos() can be used with arbitrarily huge files. fgetpos() and fsetpos() also record the state associated with multibyte streams. See also question 1.4. References: K&R2 Sec. B1.6 p. 248; ISO Sec. 7.9.1, Secs. <IP_ADDRESS>,<IP_ADDRESS>; H&S Sec. 15.5 p. 252. 12.26: How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will fflush(stdin) work? A: fflush() is defined only for output streams. Since its definition of "flush" is to complete the writing of buffered characters (not to discard them), discarding unread input would not be an analogous meaning for fflush on input streams. There is no standard way to discard unread characters from a stdio input stream, nor would such a way necessarily be sufficient, since unread characters can also accumulate in other, OS-level input buffers. You may be able to read and discard characters until \n, or use the curses flushinp() function, or use some system-specific technique. See also questions 19.1 and 19.2. References: ISO Sec. <IP_ADDRESS>; H&S Sec. 15.2. 12.30: I'm trying to update a file in place, by using fopen mode "r+", reading a certain string, and writing back a modified string, but it's not working. A: Be sure to call fseek before you write, both to seek back to the beginning of the string you're trying to overwrite, and because an fseek or fflush is always required between reading and writing in the read/write "+" modes. Also, remember that you can only overwrite characters with the same number of replacement characters, and that overwriting in text mode may truncate the file at that point. See also question 19.14. References: ISO Sec. <IP_ADDRESS>. 12.33: How can I redirect stdin or stdout to a file from within a program? A: Use freopen() (but see question 12.34 below). References: ISO Sec. <IP_ADDRESS>; H&S Sec. 15.2. 12.34: Once I've used freopen(), how can I get the original stdout (or stdin) back? A: There isn't a good way. If you need to switch back, the best solution is not to have used freopen() in the first place. Try using your own explicit output (or input) stream variable, which you can reassign at will, while leaving the original stdout (or stdin) undisturbed. It is barely possible to save away information about a stream before calling freopen(), such that the original stream can later be restored, but the methods involve system-specific calls such as dup(), or copying or inspecting the contents of a FILE structure, which is exceedingly nonportable and unreliable. 12.36b: How can I arrange to have output go two places at once, e.g. to the screen and to a file? A: You can't do this directly, but you could write your own printf variant which printed everything twice. See question 15.5. 12.38: How can I read a binary data file properly? I'm occasionally seeing 0x0a and 0x0d values getting garbled, and I seem to hit EOF prematurely if the data contains the value 0x1a. A: When you're reading a binary data file, you should specify "rb" mode when calling fopen(), to make sure that text file translations do not occur. Similarly, when writing binary data files, use "wb". Note that the text/binary distinction is made when you open the file: once a file is open, it doesn't matter which I/O calls you use on it. See also question 20.5. References: ISO Sec. <IP_ADDRESS>; H&S Sec. 15.2.1 p. 348. Section 13. Library Functions 13.1: How can I convert numbers to strings (the opposite of atoi)? Is there an itoa() function? A: Just use sprintf(). (Don't worry that sprintf() may be overkill, potentially wasting run time or code space; it works well in practice.) See the examples in the answer to question 7.5a; see also question 12.21. You can obviously use sprintf() to convert long or floating- point numbers to strings as well (using %ld or %f). References: K&R1 Sec. 3.6 p. 60; K&R2 Sec. 3.6 p. 64. 13.2: Why does strncpy() not always place a '\0' terminator in the destination string? A: strncpy() was first designed to handle a now-obsolete data structure, the fixed-length, not-necessarily-\0-terminated "string." (A related quirk of strncpy's is that it pads short strings with multiple \0's, out to the specified length.) strncpy() is admittedly a bit cumbersome to use in other contexts, since you must often append a '\0' to the destination string by hand. You can get around the problem by using strncat() instead of strncpy(): if the destination string starts out empty, strncat() does what you probably wanted strncpy() to do. Another possibility is sprintf(dest, "%.*s", n, source) . When arbitrary bytes (as opposed to strings) are being copied, memcpy() is usually a more appropriate function to use than strncpy(). 13.5: Why do some versions of toupper() act strangely if given an upper-case letter? Why does some code call islower() before toupper()? A: Older versions of toupper() and tolower() did not always work correctly on arguments which did not need converting (i.e. on digits or punctuation or letters already of the desired case). In ANSI/ISO Standard C, these functions are guaranteed to work appropriately on all character arguments. References: ISO Sec. 7.3.2; H&S Sec. 12.9 pp. 320-1; PCS p. 182. 13.6: How can I split up a string into whitespace-separated fields? How can I duplicate the process by which main() is handed argc and argv? A: The only Standard function available for this kind of "tokenizing" is strtok(), although it can be tricky to use and it may not do everything you want it to. (For instance, it does not handle quoting.) References: K&R2 Sec. B3 p. 250; ISO Sec. <IP_ADDRESS>; H&S Sec. 13.7 pp. 333-4; PCS p. 178. 13.7: I need some code to do regular expression and wildcard matching. A: Make sure you recognize the difference between classic regular expressions (variants of which are used in such Unix utilities as ed and grep), and filename wildcards (variants of which are used by most operating systems). There are a number of packages available for matching regular expressions. Most packages use a pair of functions, one for "compiling" the regular expression, and one for "executing" it (i.e. matching strings against it). Look for header files named <regex.h> or <regexp.h>, and functions called regcmp/regex, regcomp/regexec, or re_comp/re_exec. (These functions may exist in a separate regexp library.) A popular, freely- redistributable regexp package by Henry Spencer is available from ftp.cs.toronto.edu in pub/regexp.shar.Z or in several other archives. The GNU project has a package called rx. See also question 18.16. Filename wildcard matching (sometimes called "globbing") is done in a variety of ways on different systems. On Unix, wildcards are automatically expanded by the shell before a process is invoked, so programs rarely have to worry about them explicitly. Under MS-DOS compilers, there is often a special object file which can be linked in to a program to expand wildcards while argv is being built. Several systems (including MS-DOS and VMS) provide system services for listing or opening files specified by wildcards. Check your compiler/library documentation. See also questions 19.20 and 20.3. 13.8: I'm trying to sort an array of strings with qsort(), using strcmp() as the comparison function, but it's not working. A: By "array of strings" you probably mean "array of pointers to char." The arguments to qsort's comparison function are pointers to the objects being sorted, in this case, pointers to pointers to char. strcmp(), however, accepts simple pointers to char. Therefore, strcmp() can't be used directly. Write an intermediate comparison function like this: /* compare strings via pointers */ int pstrcmp(const void *p1, const void *p2) { return strcmp(*(char * const *)p1, *(char * const *)p2); } The comparison function's arguments are expressed as "generic pointers," const void *. They are converted back to what they "really are" (pointers to pointers to char) and dereferenced, yielding char *'s which can be passed to strcmp(). (Don't be misled by the discussion in K&R2 Sec. 5.11 pp. 119-20, which is not discussing the Standard library's qsort). References: ISO Sec. <IP_ADDRESS>; H&S Sec. 20.5 p. 419. 13.9: Now I'm trying to sort an array of structures with qsort(). My comparison function takes pointers to structures, but the compiler complains that the function is of the wrong type for qsort(). How can I cast the function pointer to shut off the warning? A: The conversions must be in the comparison function, which must be declared as accepting "generic pointers" (const void *) as discussed in question 13.8 above. The comparison function might look like int mystructcmp(const void *p1, const void *p2) { const struct mystruct *sp1 = p1; const struct mystruct *sp2 = p2; /* now compare sp1->whatever and sp2-> ... */ (The conversions from generic pointers to struct mystruct pointers happen in the initializations sp1 = p1 and sp2 = p2; the compiler performs the conversions implicitly since p1 and p2 are void pointers.) If, on the other hand, you're sorting pointers to structures, you'll need indirection, as in question 13.8: sp1 = *(struct mystruct * const *)p1 .  Compiler warnings are usually trying to tell you something, and unless you really know what you're doing, you ignore or muzzle them at your peril. See also question 4.9. References: ISO Sec. <IP_ADDRESS>; H&S Sec. 20.5 p. 419. 13.10: How can I sort a linked list? A: Sometimes it's easier to keep the list in order as you build it (or perhaps to use a tree instead). Algorithms like insertion sort and merge sort lend themselves ideally to use with linked lists. If you want to use a standard library function, you can allocate a temporary array of pointers, fill it in with pointers to all your list nodes, call qsort(), and finally rebuild the list pointers based on the sorted array. References: Knuth Sec. 5.2.1 pp. 80-102, Sec. 5.2.4 pp. 159-168; Sedgewick Sec. 8 pp. 98-100, Sec. 12 pp. 163-175. 13.11: How can I sort more data than will fit in memory? A: You want an "external sort," which you can read about in Knuth, Volume 3. The basic idea is to sort the data in chunks (as much as will fit in memory at one time), write each sorted chunk to a temporary file, and then merge the files. Your operating system may provide a general-purpose sort utility, and if so, you can try invoking it from within your program: see questions 19.27 and 19.30. References: Knuth Sec. 5.4 pp. 247-378; Sedgewick Sec. 13 pp. 177-187. 13.12: How can I get the current date or time of day in a C program? A: Just use the time(), ctime(), localtime() and/or strftime() functions. Here is a simple example: #include <stdio.h> #include <time.h> int main() { time_t now; time(&now); printf("It's %.24s.\n", ctime(&now)); return 0; } References: K&R2 Sec. B10 pp. 255-7; ISO Sec. 7.12; H&S Sec. 18. 13.13: I know that the library function 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 function, mktime(), which converts a struct tm to a time_t. Converting a string to a time_t is harder, because of the wide variety of date and time formats which might be encountered. Some systems provide a strptime() function, which is basically the inverse of strftime(). Other popular functions are partime() (widely distributed with the RCS package) and getdate() (and a few others, from the C news distribution). See question 18.16. References: K&R2 Sec. B10 p. 256; ISO Sec. <IP_ADDRESS>; H&S Sec. 18.4 pp. 401-2. 13.14: How can I add N days to a date? How can I find the difference between two dates? A: The ANSI/ISO Standard C mktime() and difftime() functions provide some support for both problems. mktime() accepts non- normalized dates, so it is straightforward to take a filled-in struct tm, add or subtract from the tm_mday field, and call mktime() to normalize the year, month, and day fields (and incidentally convert to a time_t value). difftime() computes the difference, in seconds, between two time_t values; mktime() can be used to compute time_t values for two dates to be subtracted. These solutions are only guaranteed to work correctly for dates in the range which can be represented as time_t's. The tm_mday field is an int, so day offsets of more than 32,736 or so may cause overflow. Note also that at daylight saving time changeovers, local days are not 24 hours long (so don't assume that division by 86400 will be exact). Another approach to both problems is to use "Julian day numbers". Code for handling Julian day numbers can be found in the Snippets collection (see question 18.15c), the Simtel/Oakland archives (file JULCAL10.ZIP, see question 18.16), and the "Date conversions" article mentioned in the References. See also questions 13.13, 20.31, and 20.32. References: K&R2 Sec. B10 p. 256; ISO Secs. <IP_ADDRESS>,<IP_ADDRESS>; H&S Secs. 18.4,18.5 pp. 401-2; David Burki, "Date Conversions". 13.14b: Does C have any Year 2000 problems? A: No, although poorly-written C programs do. The tm_year field of struct tm holds the value of the year minus 1900; this field will therefore contain the value 100 for the year 2000. Code that uses tm_year correctly (by adding or subtracting 1900 when converting to or from human-readable 4-digit year representations) will have no problems at the turn of the millennium. Any code that uses tm_year incorrectly, however, such as by using it directly as a human-readable 2-digit year, or setting it from a 4-digit year with code like tm.tm_year = yyyy % 100; /* WRONG */ or printing it as an allegedly human-readable 4-digit year with code like printf("19%d", tm.tm_year); /* WRONG */ will have grave y2k problems indeed. See also question 20.32. References: K&R2 Sec. B10 p. 255; ISO Sec. 7.12.1; H&S Sec. 18.4 p. 401. 13.15: I need a random number generator. A: The Standard C library has one: rand(). The implementation on your system may not be perfect, but writing a better one isn't necessarily easy, either. If you do find yourself needing to implement your own random number generator, there is plenty of literature out there; see the References. There are also any number of packages on the net: look for r250, RANLIB, and FSULTRA (see question 18.16). References: K&R2 Sec. 2.7 p. 46, Sec. 7.8.7 p. 168; ISO Sec. <IP_ADDRESS>; H&S Sec. 17.7 p. 393; PCS Sec. 11 p. 172; Knuth Vol. 2 Chap. 3 pp. 1-177; Park and Miller, "Random Number Generators: Good Ones are Hard to Find". 13.16: How can I get random integers in a certain range? A: The obvious way, rand() % N /* POOR */ (which tries to return numbers from 0 to N-1) is poor, because the low-order bits of many random number generators are distressingly *non*-random. (See question 13.18.) A better method is something like (int)((double)rand() / ((double)RAND_MAX + 1) * N) If you're worried about using floating point, you could use rand() / (RAND_MAX / N + 1) Both methods obviously require knowing RAND_MAX (which ANSI #defines in <stdlib.h>), and assume that N is much less than RAND_MAX. (Note, by the way, that RAND_MAX is a *constant* telling you what the fixed range of the C library rand() function is. You cannot set RAND_MAX to some other value, and there is no way of requesting that rand() return numbers in some other range.) If you're starting with a random number generator which returns floating-point values between 0 and 1, all you have to do to get integers from 0 to N-1 is multiply the output of that generator by N. References: K&R2 Sec. 7.8.7 p. 168; PCS Sec. 11 p. 172. 13.17: Each time I run my program, I get the same sequence of numbers back from rand(). A: You can call srand() to seed the pseudo-random number generator with a truly random initial value. Popular seed values are the time of day, or the elapsed time before the user presses a key (although keypress times are hard to determine portably; see question 19.37). (Note also that it's rarely useful to call srand() more than once during a run of a program; in particular, don't try calling srand() before each call to rand(), in an attempt to get "really random" numbers.) References: K&R2 Sec. 7.8.7 p. 168; ISO Sec. <IP_ADDRESS>; H&S Sec. 17.7 p. 393. 13.18: I need a random true/false value, so I'm just taking rand() % 2, but it's alternating 0, 1, 0, 1, 0... A: Poor pseudorandom number generators (such as the ones unfortunately supplied with some systems) are not very random in the low-order bits. Try using the higher-order bits: see question 13.16. References: Knuth Sec. <IP_ADDRESS> pp. 12-14. 13.20: How can I generate random numbers with a normal or Gaussian distribution? A: Here is one method, recommended by Knuth and due originally to Marsaglia: #include <stdlib.h> #include <math.h> double gaussrand() { static double V1, V2, S; static int phase = 0; double X; if(phase == 0) { do { double U1 = (double)rand() / RAND_MAX; double U2 = (double)rand() / RAND_MAX; V1 = 2 * U1 - 1; V2 = 2 * U2 - 1; S = V1 * V1 + V2 * V2; } while(S >= 1 || S == 0); X = V1 * sqrt(-2 * log(S) / S); } else X = V2 * sqrt(-2 * log(S) / S); phase = 1 - phase; return X; } See the extended versions of this list (see question 20.40) for other ideas. References: Knuth Sec. 3.4.1 p. 117; Marsaglia and Bray, "A Convenient Method for Generating Normal Variables"; Press et al., _Numerical Recipes in C_ Sec. 7.2 pp. 288-290. 13.24: I'm trying to port this A: Those functions are variously old program. Why do I obsolete; you should get "undefined external" instead: errors for: index? use strchr. rindex? use strrchr. bcopy? use memmove, after interchanging the first and second arguments (see also question 11.25). bcmp? use memcmp. bzero? use memset, with a second argument of 0. References: PCS Sec. 11. 13.25: I keep getting errors due to library functions being undefined, but I'm #including all the right header files. A: In general, a header file contains only declarations. In some cases (especially if the functions are nonstandard) obtaining the actual *definitions* may require explicitly asking for the correct libraries to be searched when you link the program. (#including the header doesn't do that.) See also questions 11.30, 13.26, and 14.3. 13.26: I'm still getting errors due to library functions being undefined, even though I'm explicitly requesting the right libraries while linking. A: Many linkers make one pass over the list of object files and libraries you specify, and extract from libraries only those modules which satisfy references which have so far come up as undefined. Therefore, the order in which libraries are listed with respect to object files (and each other) is significant; usually, you want to search the libraries last. (For example, under Unix, put any -l options towards the end of the command line.) See also question 13.28. 13.28: What does it mean when the linker says that _end is undefined? A: That message is a quirk of the old Unix linkers. You get an error about _end being undefined only when other symbols are undefined, too -- fix the others, and the error about _end will disappear. (See also questions 13.25 and 13.26.) Section 14. Floating Point 14.1: When I set a float variable to, say, 3.1, why is printf printing it as 3.0999999? A: Most computers use base 2 for floating-point numbers as well as for integers. In base 2, one divided by ten is an infinitely- repeating fraction (0.0001100110011...), so fractions such as 3.1 (which look like they can be exactly represented in decimal) cannot be represented exactly in binary. Depending on how carefully your compiler's binary/decimal conversion routines (such as those used by printf) have been written, you may see discrepancies when numbers (especially low-precision floats) not exactly representable in base 2 are assigned or read in and then printed (i.e. converted from base 10 to base 2 and back again). See also question 14.6. 14.2: I'm trying to take some square roots, but I'm getting crazy numbers. A: Make sure that you have #included <math.h>, and correctly declared other functions returning double. (Another library function to be careful with is atof(), which is declared in <stdlib.h>.) See also question 14.3 below. References: CT&P Sec. 4.5 pp. 65-6. 14.3: I'm trying to do some simple trig, and I am #including <math.h>, but I keep getting "undefined: sin" compilation errors. A: Make sure you're actually linking with the math library. For instance, under Unix, you usually need to use the -lm option, at the *end* of the command line, when compiling/linking. See also questions 13.25, 13.26, and 14.2. 14.4: My floating-point calculations are acting strangely and giving me different answers on different machines. A: First, see question 14.2 above. If the problem isn't that simple, recall that digital computers usually use floating-point formats which provide a close but by no means exact simulation of real number arithmetic. Underflow, cumulative precision loss, and other anomalies are often troublesome. 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; see question 14.5.) These problems are no worse for C than they are for any other computer language. Certain aspects of floating-point are usually defined as "however the processor does them" (see also question 11.34), 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 numerical programming text should cover the basics; see also the references below. References: Kernighan and Plauger, _The Elements of Programming Style_ Sec. 6 pp. 115-8; Knuth, Volume 2 chapter 4; David Goldberg, "What Every Computer Scientist Should Know about Floating-Point Arithmetic". 14.5: What's a good way to check for "close enough" floating-point equality? A: Since the absolute accuracy of floating point values varies, by definition, with their magnitude, the best way of comparing two floating point values is to use an accuracy threshold which is relative to the magnitude of the numbers being compared. Rather than double a, b; ... if(a == b) /* WRONG */ use something like #include <math.h> if(fabs(a - b) <= epsilon * fabs(a)) for some suitably-chosen degree of closeness epsilon (as long as a is nonzero!). References: Knuth Sec. 4.2.2 pp. 217-8. 14.6: How do I round numbers? A: The simplest and most straightforward way is with code like (int)(x + 0.5) This technique won't work properly for negative numbers, though (for which you could use something like (int)(x < 0 ? x - 0.5 : x + 0.5)). 14.7: Why doesn't C have an exponentiation operator? A: Because few processors have an exponentiation instruction. C has a pow() function, declared in <math.h>, although explicit multiplication is usually better for small positive integral exponents. References: ISO Sec. <IP_ADDRESS>; H&S Sec. 17.6 p. 393. 14.8: The predefined constant M_PI seems to be missing from my machine's copy of <math.h>. A: That constant (which is apparently supposed to be the value of pi, accurate to the machine's precision), is not standard. If you need pi, you'll have to define it yourself, or compute it with 4*atan(1.0). References: PCS Sec. 13 p. 237. 14.9: How do I test for IEEE NaN and other special values? A: Many systems with high-quality IEEE floating-point implementations provide facilities (e.g. predefined constants, and functions like isnan(), either as nonstandard extensions in <math.h> or perhaps in <ieee.h> or <nan.h>) to deal with these values cleanly, and work is being done to formally standardize such facilities. A crude but usually effective test for NaN is exemplified by #define isnan(x) ((x) != (x)) although non-IEEE-aware compilers may optimize the test away. C9X will provide isnan(), fpclassify(), and several other classification routines. Another possibility is to to format the value in question using sprintf(): on many systems it generates strings like "NaN" and "Inf" which you could compare for in a pinch. See also question 19.39. References: C9X Sec. 7.7.3. 14.11: What's a good way to implement complex numbers in C? A: It is straightforward to define a simple structure and some arithmetic functions to manipulate them. C9X will support complex as a standard type. See also questions 2.7, 2.10, and 14.12. References: C9X Sec. <IP_ADDRESS>, Sec. 7.8. 14.12: I'm looking for some code to do: Fast Fourier Transforms (FFT's) matrix arithmetic (multiplication, inversion, etc.) complex arithmetic A: Ajay Shah has prepared a nice index of free numerical software which has been archived pretty widely; one URL is ftp://ftp.math.psu.edu/pub/FAQ/numcomp-free-c . See also questions 18.13, 18.15c, and 18.16. 14.13: I'm having trouble with a Turbo C program which crashes and says something like "floating point formats not linked." A: Some compilers for small machines, including Borland's (and Ritchie's original PDP-11 compiler), leave out certain 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 Borland's heuristics for determining whether the program uses floating point are insufficient, and the programmer must sometimes insert a dummy call to a floating-point library function (such as sqrt(); any will do) to force loading of floating-point support. (See the comp.os.msdos.programmer FAQ list for more information.) Section 15. Variable-Length Argument Lists 15.1: I heard that you have to #include <stdio.h> before calling printf(). Why? A: So that a proper prototype for printf() will be in scope. A compiler may use a different calling sequence for functions which accept variable-length argument lists. (It might do so if calls using variable-length argument lists were less efficient than those using fixed-length.) Therefore, a prototype (indicating, using the ellipsis notation "...", that the argument list is of variable length) must be in scope whenever a varargs function is called, so that the compiler knows to use the varargs calling mechanism. References: ISO Sec. <IP_ADDRESS>, Sec. 7.1.7; Rationale Sec. <IP_ADDRESS>, Sec. 4.1.6; H&S Sec. 9.2.4 pp. 268-9, Sec. 9.6 pp. 275-6. 15.2: How can %f be used for both float and double arguments in printf()? Aren't they different types? A: In the variable-length part of a variable-length argument list, the "default argument promotions" apply: types char and short int are promoted to int, and float is promoted to double. (These are the same promotions that apply to function calls without a prototype in scope, also known as "old style" function calls; see question 11.3.) Therefore, printf's %f format always sees a double. (Similarly, %c always sees an int, as does %hd.) See also questions 12.9 and 12.13. References: ISO Sec. <IP_ADDRESS>; H&S Sec. 6.3.5 p. 177, Sec. 9.4 pp. 272-3. 15.3: I had a frustrating problem which turned out to be caused by the line printf("%d", n); where n was actually a long int. I thought that ANSI function prototypes were supposed to guard against argument type mismatches like this. A: When a function accepts a variable number of arguments, its prototype does not (and cannot) provide any information about the number and types of those variable arguments. Therefore, the usual protections do *not* apply in the variable-length part of variable-length argument lists: the compiler cannot perform implicit conversions or (in general) warn about mismatches. See also questions 5.2, 11.3, 12.9, and 15.2. 15.4: How can I write a function that takes a variable number of arguments? A: Use the facilities of the <stdarg.h> header. Here is a function which concatenates an arbitrary number of strings into malloc'ed memory: #include <stdlib.h> /* for malloc, NULL, size_t */ #include <stdarg.h> /* for va_ stuff */ #include <string.h> /* for strcat et al. */ char *vstrcat(char *first, ...) { size_t len; 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); /* restart; 2nd scan */ 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; see questions 5.2 and 15.3. (Also note that the caller must free the returned, malloc'ed storage.) See also question 15.7. References: K&R2 Sec. 7.3 p. 155, Sec. B7 p. 254; ISO Sec. 7.8; Rationale Sec. 4.8; H&S Sec. 11.4 pp. 296-9; CT&P Sec. A.3 pp. 139-141; PCS Sec. 11 pp. 184-5, Sec. 13 p. 242. 15.5: 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() function 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"); } See also question 15.7. References: K&R2 Sec. 8.3 p. 174, Sec. B1.2 p. 245; ISO Secs. <IP_ADDRESS>,<IP_ADDRESS>,<IP_ADDRESS>; H&S Sec. 15.12 pp. 379-80; PCS Sec. 11 pp. 186-7. 15.6: How can I write a function analogous to scanf(), that calls scanf() to do most of the work? A: C9X will support vscanf(), vfscanf(), and vsscanf(). (Until then, you may be on your own.) References: C9X Secs. <IP_ADDRESS>-14. 15.7: I have a pre-ANSI compiler, without <stdarg.h>. What can I do? A: There's an older header, <varargs.h>, which offers about the same functionality. References: H&S Sec. 11.4 pp. 296-9; CT&P Sec. A.2 pp. 134-139; PCS Sec. 11 pp. 184-5, Sec. 13 p. 250. 15.8: How can I discover how many arguments a function was actually called with? A: This information is not available to a portable program. Some old systems provided a nonstandard nargs() function, but its use was always questionable, since it typically returned the number of words passed, not the number of arguments. (Structures, long ints, and floating point values 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, applicable 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 in questions 5.2 and 15.4). Finally, if their types are predictable, you can pass an explicit count of the number of variable arguments (although it's usually a nuisance for the caller to supply). References: PCS Sec. 11 pp. 167-8. 15.9: My compiler isn't letting me declare a function int f(...) { } i.e. with no fixed arguments. A: Standard C requires at least one fixed argument, in part so that you can hand it to va_start(). See also question 15.10. References: ISO Sec. 6.5.4, Sec. <IP_ADDRESS>, Sec. <IP_ADDRESS>; H&S Sec. 9.2 p. 263. 15.10: I have a varargs function which accepts a float parameter. Why isn't va_arg(argp, float) working? A: In the variable-length part of variable-length argument lists, the old "default argument promotions" apply: arguments of type float are always promoted (widened) to type double, and types char and short int are promoted to int. Therefore, it is never correct to invoke va_arg(argp, float); instead you should always use va_arg(argp, double). Similarly, use va_arg(argp, int) to retrieve arguments which were originally char, short, or int. (For analogous reasons, the last "fixed" argument, as handed to va_start(), should not be widenable, either.) See also questions 11.3 and 15.2. References: ISO Sec. <IP_ADDRESS>; Rationale Sec. <IP_ADDRESS>; H&S Sec. 11.4 p. 297. 15.11: I can't get va_arg() to pull in an argument of type pointer-to- function. A: The type-rewriting games which the va_arg() macro typically plays are stymied by overly-complicated types such as pointer-to- function. If you use a typedef for the function pointer type, however, all will be well. See also question 1.21. References: ISO Sec. <IP_ADDRESS>; Rationale Sec. <IP_ADDRESS>. 15.12: 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. Ideally, you should provide a version of that other function which accepts a va_list pointer (analogous to vfprintf(); see question 15.5 above). If the arguments must be passed directly as actual arguments, or if you do not have the option of rewriting the second function to accept a va_list (in other words, if the second, called function must accept a variable number of arguments, not a va_list), no portable solution is possible. (The problem could perhaps be solved by resorting to machine-specific assembly language; see also question 15.13 below.) 15.13: How can I call a function with an argument list built up at run time? A: There is no guaranteed or portable way to do this. If you're curious, ask this list's editor, who has a few wacky ideas you could try... Instead of an actual argument list, you might consider passing an array of generic (void *) pointers. The called function can then step through the array, much like main() might step through argv. (Obviously this works only if you have control over all the called functions.) (See also question 19.36.) Section 16. Strange Problems 16.1b: I'm getting baffling syntax errors which make no sense at all, and it seems like large chunks of my program aren't being compiled. A: Check for unclosed comments or mismatched #if/#ifdef/#ifndef/ #else/#endif directives; remember to check header files, too. (See also questions 2.18, 10.9, and 11.29.) 16.1c: Why isn't my procedure call working? The compiler seems to skip right over it. A: Does the code look like this? myprocedure; C has only functions, and function calls always require parenthesized argument lists, even if empty. Use myprocedure(); 16.3: 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, in which case you could dynamically allocate them with malloc(); see also question 1.31). (See also questions 11.12b, 16.4, 16.5, and 18.4.) 16.4: I have a program that seems to run correctly, but it crashes as it's exiting, *after* the last statement in main(). What could be causing this? A: Look for a misdeclared main() (see questions 2.18 and 10.9), or local buffers passed to setbuf() or setvbuf(), or problems in cleanup functions registered by atexit(). See also questions 7.5a and 11.16. References: CT&P Sec. 5.3 pp. 72-3. 16.5: This program runs perfectly on one machine, but I get weird results on another. Stranger still, adding or removing a debugging printout changes the symptoms... A: Lots of things could be going wrong; here are a few of the more common things to check: uninitialized local variables (see also question 7.1) integer overflow, especially on 16-bit machines, especially of an intermediate result when doing things like a * b / c (see also question 3.14) undefined evaluation order (see questions 3.1 through 3.4) omitted declaration of external functions, especially those which return something other than int, or have "narrow" or variable arguments (see questions 1.25, 11.3, 14.2, and 15.1) dereferenced null pointers (see section 5) improper malloc/free use: assuming malloc'ed memory contains 0, assuming freed storage persists, freeing something twice, corrupting the malloc arena (see also questions 7.19 and 7.20) pointer problems in general (see also question 16.8) mismatch between printf() format and arguments, especially trying to print long ints using %d (see question 12.9) trying to allocate more memory than an unsigned int can count, especially on machines with limited memory (see also questions 7.16 and 19.23) array bounds problems, especially of small, temporary buffers, perhaps used for constructing strings with sprintf() (see also questions 7.1 and 12.21) invalid assumptions about the mapping of typedefs, especially size_t floating point problems (see questions 14.1 and 14.4) anything you thought was a clever exploitation of the way you believe code is generated for your specific system Proper use of function prototypes can catch several of these problems; lint would catch several more. See also questions 16.3, 16.4, and 18.4. 16.6: Why does this code: char *p = "hello, world!"; p[0] = 'H'; crash? A: String literals are not necessarily modifiable, except (in effect) when they are used as array initializers. Try char a[] = "hello, world!"; See also question 1.32. References: ISO Sec. 6.1.4; H&S Sec. 2.7.4 pp. 31-2. 16.8: What do "Segmentation violation" and "Bus error" mean? A: These generally mean that your program tried to access memory it shouldn't have, invariably as a result of stack corruption or improper pointer use. Likely causes are overflow of local ("automatic," stack-allocated) arrays; inadvertent use of null pointers (see also questions 5.2 and 5.20) or uninitialized, misaligned, or otherwise improperly allocated pointers (see questions 7.1 and 7.2); corruption of the malloc arena (see question 7.19); and mismatched function arguments, especially involving pointers; two possibilities are scanf() (see question 12.12) and fprintf() (make sure it receives its first FILE * argument). See also questions 16.3 and 16.4. Section 17. Style 17.1: 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 disregarding 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.) The elusive quality of "good style" involves much more than mere code layout details; don't spend time on formatting to the exclusion of more substantive code quality issues. See also question 10.6. References: K&R1 Sec. 1.2 p. 10; K&R2 Sec. 1.2 p. 10. 17.3: Here's a neat trick for checking whether two strings are equal: if(!strcmp(s1, s2)) Is this good style? A: It is not particularly good style, although it is a popular idiom. The test succeeds if the two strings are equal, but the use of ! ("not") suggests that it tests for inequality. Another option is to use a macro: #define Streq(s1, s2) (strcmp((s1), (s2)) == 0) See also question 17.10. 17.4: Why do some people write if(0 == x) instead of if(x == 0)? A: It's a trick to guard against the common error of writing if(x = 0) If you're in the habit of writing the constant before the ==, the compiler will complain if you accidentally type if(0 = x) Evidently it can be easier for some people to remember to reverse the test than to remember to type the doubled = sign. (Of course, the trick only helps when comparing to a constant.) References: H&S Sec. 7.6.5 pp. 209-10. 17.5: I came across some code that puts a (void) cast before each call to printf(). Why? A: printf() does return a value, though few programs bother to check the return values from each call. Since some compilers (and lint) will warn about discarded return values, an explicit cast to (void) is a way of saying "Yes, I've decided to ignore the return value from this call, but please continue to warn me about other (perhaps inadvertently) ignored return values." It's also common to use void casts on calls to strcpy() and strcat(), since the return value is never surprising. References: K&R2 Sec. A6.7 p. 199; Rationale Sec. 3.3.4; H&S Sec. 6.2.9 p. 172, Sec. 7.13 pp. 229-30. 17.8: What is "Hungarian Notation"? Is it worthwhile? A: Hungarian Notation is a naming convention, invented by Charles Simonyi, which encodes information about a variable's type (and perhaps its intended use) in its name. It is well-loved in some circles and roundly castigated in others. Its chief advantage is that it makes a variable's type or intended use obvious from its name; its chief disadvantage is that type information is not necessarily a worthwhile thing to carry around in the name of a variable. References: Simonyi and Heller, "The Hungarian Revolution" . 17.9: 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: ftp.cs.washington.edu pub/cstyle.tar.Z (the updated Indian Hill guide) ftp.cs.toronto.edu doc/programming (including Henry Spencer's "10 Commandments for C Programmers") ftp.cs.umd.edu pub/style-guide You may also be interested in the books _The Elements of Programming Style_, _Plum Hall Programming Guidelines_, and _C Style: Standards and Guidelines_; see the Bibliography. See also question 18.9. 17.10: Some people say that goto's are evil and that I should never use them. Isn't that a bit extreme? A: Programming style, like writing style, is somewhat of an art and cannot be codified by inflexible rules, although discussions about style often seem to center exclusively around such rules. In the case of the goto statement, it has long been observed that unfettered use of goto's quickly leads to unmaintainable spaghetti code. However, a simple, unthinking ban on the goto statement does not necessarily lead immediately to beautiful programming: an unstructured programmer is just as capable of constructing a Byzantine tangle without using any goto's (perhaps substituting oddly-nested loops and Boolean control variables, instead). Most observations or "rules" about programming style usually work better as guidelines than rules, and work much better if programmers understand what the guidelines are trying to accomplish. Blindly avoiding certain constructs or following rules without understanding them can lead to just as many problems as the rules were supposed to avert. Furthermore, many opinions on programming style are just that: opinions. It's usually futile to get dragged into "style wars," because on certain issues (such as those referred to in questions 9.2, 5.3, 5.9, and 10.7), opponents can never seem to agree, or agree to disagree, or stop arguing. Section 18. Tools and Resources 18.1: I need: A: Look for programs (see also question 18.16) named: a C cross-reference cflow, cxref, calls, cscope, generator xscope, or ixfw a C beautifier/pretty- cb, indent, GNU indent, or printer vgrind a revision control or CVS, RCS, or SCCS configuration management tool a C source obfuscator obfus, shroud, or opqcp (shrouder) a "make" dependency makedepend, or try cc -M or generator cpp -M tools to compute code ccount, Metre, lcount, or csize, metrics or see URL http://www.qucis.queensu.ca/ Software-Engineering/Cmetrics.html ; there is also a package sold by McCabe and Associates a C lines-of-source this can be done very counter crudely with the standard Unix utility wc, and somewhat better with grep -c ";" a C declaration aid check volume 14 of (cdecl) comp.sources.unix (see question 18.16) and K&R2 a prototype generator see question 11.31 a tool to track down malloc problems see question 18.2 a "selective" C preprocessor see question 10.18 language translation see questions 11.31 and tools 20.26 C verifiers (lint) see question 18.7 a C compiler! see question 18.3 (This list of tools is by no means complete; if you know of tools not mentioned, you're welcome to contact this list's maintainer.) Other lists of tools, and discussion about them, can be found in the Usenet newsgroups comp.compilers and comp.software-eng. See also questions 18.3 and 18.16. 18.2: How can I track down these pesky malloc problems? A: A number of debugging packages exist to help track down malloc problems; one popular one is Conor P. Cahill's "dbmalloc", posted to comp.sources.misc in 1992, volume 32. Others are "leak", available in volume 27 of the comp.sources.unix archives; JMalloc.c and JMalloc.h in the "Snippets" collection; and MEMDEBUG from ftp.crpht.lu in pub/sources/memdebug . See also question 18.16. A number of commercial debugging tools exist, and can be invaluable in tracking down malloc-related and other stubborn problems: Bounds-Checker for DOS, from Nu-Mega Technologies, P.O. Box 7780, Nashua, NH 03060-7780, USA,<PHONE_NUMBER>. CodeCenter (formerly Saber-C) from Centerline Software, 10 Fawcett Street, Cambridge, MA 02138, USA,<PHONE_NUMBER>. Insight, from ParaSoft Corporation, 2500 E. Foothill Blvd., Pasadena, CA 91107, USA,<PHONE_NUMBER><EMAIL_ADDRESS>. Purify, from Pure Software, 1309 S. Mary Ave., Sunnyvale, CA 94087, USA,<PHONE_NUMBER>, http://www.pure.com<EMAIL_ADDRESS>. (I believe Pure was recently acquired by Rational.) Final Exam Memory Advisor, from PLATINUM Technology (formerly Sentinel from AIB Software), 1815 South Meyers Rd., Oakbrook Terrace, IL 60181, USA,<PHONE_NUMBER>,<PHONE_NUMBER><EMAIL_ADDRESS>www.platinum.com . ZeroFault, from The Kernel Group, 1250 Capital of Texas Highway South, Building Three, Suite 601, Austin, TX 78746,<PHONE_NUMBER>, http://www.tkg.com<EMAIL_ADDRESS>. 18.3: What's a free or cheap C compiler I can use? A: A popular and high-quality free C compiler is the FSF's GNU C compiler, or gcc. It is available by anonymous ftp from prep.ai.mit.edu in directory pub/gnu, or at several other FSF archive sites. An MS-DOS port, djgpp, is also available; see the djgpp home page at http://www.delorie.com/djgpp/ . There is a shareware compiler called PCC, available as PCC12C.ZIP . A very inexpensive MS-DOS compiler is Power C from Mix Software, 1132 Commerce Drive, Richardson, TX 75801, USA,<PHONE_NUMBER>. Another recently-developed compiler is lcc, available for anonymous ftp from ftp.cs.princeton.edu in pub/lcc/. A shareware MS-DOS C compiler is available from ftp.hitech.com.au/hitech/pacific. Registration is optional for non-commercial use. There are currently no viable shareware compilers for the Macintosh. Archives associated with comp.compilers contain a great deal of information about available compilers, interpreters, grammars, etc. (for many languages). The comp.compilers archives (including an FAQ list), maintained by the moderator, John R. Levine, are at iecc.com . A list of available compilers and related resources, maintained by Mark Hopkins, Steven Robenalt, and David Muir Sharnoff, is at ftp.idiom.com in pub/compilers- list/. (See also the comp.compilers directory in the news.answers archives at rtfm.mit.edu and ftp.uu.net; see question 20.40.) See also question 18.16. 18.4: I just typed in this program, and it's acting strangely. Can you see anything wrong with it? A: See if you can run lint first (perhaps with the -a, -c, -h, -p or other options). Many C compilers are really only half- compilers, electing not to diagnose numerous source code difficulties which would not actively preclude code generation. See also questions 16.5, 16.8, and 18.7. References: Ian Darwin, _Checking C Programs with lint_ . 18.5: How can I shut off the "warning: possible pointer alignment problem" message which 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. (But don't get in the habit of ignoring too many lint messages, otherwise one day you'll overlook a significant one.) 18.7: Where can I get an ANSI-compatible lint? A: Products called PC-Lint and FlexeLint (in "shrouded source form," for compilation on 'most any system) are available from Gimpel Software 3207 Hogarth Lane Collegeville, PA 19426 USA (+1)<PHONE_NUMBER><EMAIL_ADDRESS>The Unix System V release 4 lint is ANSI-compatible, and is available separately (bundled with other C tools) from UNIX Support Labs or from System V resellers. Another ANSI-compatible lint (which can also perform higher- level formal verification) is LCLint, available via anonymous ftp from larch.lcs.mit.edu in pub/Larch/lclint/. In the absence of lint, many modern compilers do attempt to diagnose almost as many problems as lint does. (Many netters recommend gcc -Wall -pedantic .) 18.8: Don't ANSI function prototypes render lint obsolete? A: No. First of all, prototypes work only if they are present and correct; an inadvertently incorrect prototype is worse than useless. Secondly, lint checks consistency across multiple source files, and checks data declarations as well as functions. Finally, 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. If you do want to use function prototypes instead of lint for cross-file consistency checking, make sure that you set the prototypes up correctly in header files. See questions 1.7 and 10.6. 18.9: Are there any C tutorials or other resources on the net? A: There are several of them: Tom Torfs has a nice tutorial at http://members.xoom.com/tomtorfs/cintro.html . "Notes for C programmers," by Christopher Sawtell, are available from svr-ftp.eng.cam.ac.uk in misc/sawtell_C.shar and garbo.uwasa.fi in /pc/c-lang/c-lesson.zip . Tim Love's "C for Programmers" is available by ftp from svr- ftp.eng.cam.ac.uk in the misc directory. An html version is at http://www-h.eng.cam.ac.uk/help/tpl/languages/C/teaching_C/ teaching_C.html . The Coronado Enterprises C tutorials are available on Simtel mirrors in pub/msdos/c or on the web at http://www.swcp.com/~dodrill . Rick Rowe has a tutorial which is available from ftp.netcom.com as pub/rowe/tutorde.zip or ftp.wustl.edu as pub/MSDOS_UPLOADS/programming/c_language/ctutorde.zip . There is evidently a web-based course at http://www.strath.ac.uk/CC/Courses/CCourse/CCourse.html . Martin Brown has C course material on the web at http://www-isis.ecs.soton.ac.uk/computing/c/Welcome.html . On some Unix machines you can try typing "learn c" at the shell prompt (but the lessons may be quite dated). Finally, the author of this FAQ list teaches a C class and has placed its notes on the web; they are at http://www.eskimo.com/~scs/cclass/cclass.html . [Disclaimer: I have not reviewed many of these tutorials, and I gather that they tend to contain errors. With the exception of the one with my name on it, I can't vouch for any of them. Also, this sort of information rapidly becomes out-of-date; these addresses may not work by the time you read this and try them.] Several of these tutorials, plus a great deal of other information about C, are accessible via the web at http://www.lysator.liu.se/c/index.html . Vinit Carpenter maintains a list of resources for learning C and C++; it is posted to comp.lang.c and comp.lang.c++, and archived where this FAQ list is (see question 20.40), or on the web at http://www.cyberdiem.com/vin/learn.html . See also questions 18.10 and 18.15c. 18.10: What's a good book for learning C? A: There are far too many books on C to list here; it's impossible to rate them all. Many people believe that the best one was also the first: _The C Programming Language_, by Kernighan and Ritchie ("K&R," now in its second edition). Opinions vary on K&R's suitability as an initial programming text: many of us did learn C from it, and learned it well; some, however, feel that it is a bit too clinical as a first tutorial for those without much programming background. Several sets of annotations and errata are available on the net, see e.g. http://www.csd.uwo.ca/~jamie/.Refs/.Footnotes/C-annotes.html, http://www.eskimo.com/~scs/cclass/cclass.html, and http://www.lysator.liu.se/c/c-errata.html#main . Many comp.lang.c regulars recommend _C: A Modern Approach_, by K.N. King. An excellent reference manual is _C: A Reference Manual_, by Samuel P. Harbison and Guy L. Steele, now in its fourth edition. Though not suitable for learning C from scratch, this FAQ list has been published in book form; see the Bibliography. Mitch Wright maintains an annotated bibliography of C and Unix books; it is available for anonymous ftp from ftp.rahul.net in directory pub/mitch/YABL/. Scott McMahon has a nice set of reviews at http://www.skwc.com/essent/cyberreviews.html . The Association of C and C++ Users (ACCU) maintains a comprehensive set of bibliographic reviews of C/C++ titles, at http://bach.cis.temple.edu/accu/bookcase or http://www.accu.org/accu . This FAQ list's editor has a large collection of assorted old recommendations which various people have posted; it is available upon request. See also question 18.9 above. 18.13: Where can I find the sources of the standard C libraries? A: One source (though not public domain) is _The Standard C Library_, by P.J. Plauger (see the Bibliography). Implementations of all or part of the C library have been written and are readily available as part of the NetBSD and GNU (also Linux) projects. See also questions 18.15c and 18.16. 18.13b: Is there an on-line C reference manual? A: Two possibilities are http://www.cs.man.ac.uk/standard_c/_index.html and http://www.dinkumware.com/htm_cl/index.html . 18.13c: Where can I get a copy of the ANSI/ISO C Standard? A: See question 11.2. 18.14: I need code to parse and evaluate expressions. A: Two available packages are "defunc," posted to comp.sources.misc in December, 1993 (V41 i32,33), to alt.sources in January, 1994, and available from sunsite.unc.edu in pub/packages/development/libraries/defunc-1.3.tar.Z, and "parse," at lamont.ldgo.columbia.edu. Other options include the S-Lang interpreter, available via anonymous ftp from amy.tch.harvard.edu in pub/slang, and the shareware Cmm ("C- minus-minus" or "C minus the hard stuff"). See also questions 18.16 and 20.6. There is also some parsing/evaluation code in _Software Solutions in C_ (chapter 12, pp. 235-55). 18.15: Where can I get a BNF or YACC grammar for C? A: The definitive grammar is of course the one in the ANSI standard; see question 11.2. Another grammar (along with one for C++) by Jim Roskind is in pub/c++grammar1.1.tar.Z at ics.uci.edu (or perhaps ftp.ics.uci.edu, or perhaps OLD/pub/c++grammar1.1.tar.Z), or at ftp.eskimo.com in u/s/scs/roskind_grammar.Z . A fleshed-out, working instance of the ANSI grammar (due to Jeff Lee) is on ftp.uu.net (see question 18.16) in usenet/net.sources/ansi.c.grammar.Z (including a companion lexer). The FSF's GNU C compiler contains a grammar, as does the appendix to K&R2. The comp.compilers archives contain more information about grammars; see question 18.3. References: K&R1 Sec. A18 pp. 214-219; K&R2 Sec. A13 pp. 234- 239; ISO Sec. B.2; H&S pp. 423-435 Appendix B. 18.15b: Does anyone have a C compiler test suite I can use? A: Plum Hall (formerly in Cardiff, NJ; now in Hawaii) sells one; other packages are Ronald Guilmette's RoadTest(tm) Compiler Test Suites (ftp to netcom.com, pub/rfg/roadtest/announce.txt for information) and Nullstone's Automated Compiler Performance Analysis Tool (see http://www.nullstone.com). The FSF's GNU C (gcc) distribution includes a c-torture-test which checks a number of common problems with compilers. Kahan's paranoia test, found in netlib/paranoia on netlib.att.com, strenuously tests a C implementation's floating point capabilities. 18.15c: Where are some collections of useful code fragments and examples? A: Bob Stout's popular "SNIPPETS" collection is available from ftp.brokersys.com in directory pub/snippets or on the web at http://www.brokersys.com/snippets/ . Lars Wirzenius's "publib" library is available from ftp.funet.fi in directory pub/languages/C/Publib/. See also questions 14.12, 18.9, 18.13, and 18.16. 18.15d: I need code for performing multiple precision arithmetic. A: Some popular packages are the "quad" functions within the BSD Unix libc sources (ftp.uu.net, /systems/unix/bsd-sources/..../ /src/lib/libc/quad/*), the GNU MP library, the MIRACL package (see http://indigo.ie/~mscott/ ), and the old Unix libmp.a. See also questions 14.12 and 18.16. References: Schumacher, ed., _Software Solutions in C_ Sec. 17 pp. 343-454. 18.16: Where and how can I get copies of all these freely distributable programs? A: As the number of available programs, the number of publicly accessible archive sites, and the number of people trying to access them all grow, this question becomes both easier and more difficult to answer. There are a number of large, public-spirited archive sites out there, such as ftp.uu.net, archive.umich.edu, oak.oakland.edu, sumex-aim.stanford.edu, and wuarchive.wustl.edu, which have huge amounts of software and other information all freely available. For the FSF's GNU project, the central distribution site is prep.ai.mit.edu . These well-known sites tend to be extremely busy and hard to reach, but there are also numerous "mirror" sites which try to spread the load around. On the connected Internet, the traditional way to retrieve files from an archive site is with anonymous ftp. For those without ftp access, there are also several ftp-by-mail servers in operation. More and more, the world-wide web (WWW) is being used to announce, index, and even transfer large data files. There are probably yet newer access methods, too. Those are some of the easy parts of the question to answer. The hard part is in the details -- this article cannot begin to track or list all of the available archive sites or all of the various ways of accessing them. If you have access to the net at all, you probably have access to more up-to-date information about active sites and useful access methods than this FAQ list does. The other easy-and-hard aspect of the question, of course, is simply *finding* which site has what you're looking for. There is a tremendous amount of work going on in this area, and there are probably new indexing services springing up every day. One of the first was "archie", and of course there are a number of high-profile commercial net indexing and searching services such as Alta Vista, Excite, and Yahoo. If you have access to Usenet, see the regular postings in the comp.sources.unix and comp.sources.misc newsgroups, which describe the archiving policies for those groups and how to access their archives, two of which are ftp://gatekeeper.dec.com/pub/usenet/comp.sources.unix/ and ftp://ftp.uu.net/usenet/comp.sources.unix/. The comp.archives newsgroup contains numerous announcements of anonymous ftp availability of various items. Finally, the newsgroup comp.sources.wanted is generally a more appropriate place to post queries for source availability, but check *its* FAQ list, "How to find sources," before posting there. See also questions 14.12, 18.13, and 18.15c. Section 19. System Dependencies 19.1: How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they're typed? A: Alas, there is no standard or portable way to do these things in C. Concepts such as screens and keyboards are not even mentioned in the Standard, which deals only with simple I/O "streams" of characters. At some level, interactive keyboard input is usually collected and presented to the requesting program a line at a time. This gives the operating system a chance to support input line editing (backspace/delete/rubout, etc.) in a consistent way, without requiring that it be built into every program. Only when the user is satisfied and presses the RETURN key (or equivalent) is the line made available to the calling program. Even if the calling program appears to be reading input a character at a time (with getchar() or the like), the first call blocks until the user has typed an entire line, at which point potentially many characters become available and many character requests (e.g. getchar() calls) are satisfied in quick succession. When a program wants to read each character immediately as it arrives, its course of action will depend on where in the input stream the line collection is happening and how it can be disabled. Under some systems (e.g. MS-DOS, VMS in some modes), a program can use a different or modified set of OS-level input calls to bypass line-at-a-time input processing. Under other systems (e.g. Unix, VMS in other modes), the part of the operating system responsible for serial input (often called the "terminal driver") must be placed in a mode which turns off line- at-a-time processing, after which all calls to the usual input routines (e.g. read(), getchar(), etc.) will return characters immediately. Finally, a few systems (particularly older, batch- oriented mainframes) perform input processing in peripheral processors which cannot be told to do anything other than line- at-a-time input. Therefore, when you need to do character-at-a-time input (or disable keyboard echo, which is an analogous problem), you will have to use a technique specific to the system you're using, assuming it provides one. Since comp.lang.c is oriented towards those topics that the C language has defined support for, you will usually get better answers to other questions by referring to a system-specific newsgroup such as comp.unix.questions or comp.os.msdos.programmer, and to the FAQ lists for these groups. 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. However, since these questions are frequently asked here, here are brief answers for some common situations. Some versions of curses have functions called cbreak(), noecho(), and getch() which do what you want. If you're specifically trying to read a short password without echo, you might try getpass(). Under Unix, you can 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; ECHO under all versions), or in a pinch, system() and the stty command. (For more information, see <sgtty.h> and tty(4) under classic versions, <termio.h> and termio(4) under System V, or <termios.h> and termios(4) under POSIX.) Under MS-DOS, use getch() or getche(), or the corresponding BIOS interrupts. Under VMS, try the Screen Management (SMG$) routines, or curses, or issue low-level $QIO's with the IO$_READVBLK function code (and perhaps IO$M_NOECHO, and others) to ask for one character at a time. (It's also possible to set character-at-a-time or "pass through" modes in the VMS terminal driver.) Under other operating systems, you're on your own. (As an aside, note that simply using setbuf() or setvbuf() to set stdin to unbuffered will *not* generally serve to allow character-at-a-time input.) If you're trying to write a portable program, a good approach is to define your own suite of three functions to (1) set the terminal driver or input system into character-at-a-time mode (if necessary), (2) get characters, and (3) return the terminal driver to its initial state when the program is finished. (Ideally, such a set of functions might be part of the C Standard, some day.) The extended versions of this FAQ list (see question 20.40) contain examples of such functions for several popular systems. See also question 19.2. References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1; POSIX Sec. 7. 19.2: 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 "poll", or the FIONREAD ioctl, or c_cc[VTIME], or kbhit(), or rdchk(), or the O_NDELAY option to open() or fcntl(). See also question 19.1. 19.3: How can I display a percentage-done indication that updates itself in place, or show one of those "twirling baton" progress indicators? A: These simple things, at least, you can do fairly portably. Printing the character '\r' will usually give you a carriage return without a line feed, so that you can overwrite the current line. The character '\b' is a backspace, and will usually move the cursor one position to the left. References: ISO Sec. 5.2.2. 19.4: How can I clear the screen? How can I print text in color? How can I move the cursor to a specific x, y position? A: Such things depend on the terminal type (or display) you're using. You will have to use a library such as termcap, terminfo, or curses, or some system-specific routines, to perform these operations. On MS-DOS systems, two functions to look for are clrscr() and gotoxy(). For clearing the screen, a halfway portable solution is to print a form-feed character ('\f'), which will cause some displays to clear. Even more portable (albeit even more gunky) might be to print enough newlines to scroll everything away. As a last resort, you could use system() (see question 19.27) to invoke an operating system clear-screen command. References: PCS Sec. 5.1.4 pp. 54-60, Sec. 5.1.5 pp. 60-62. 19.5: How do I read the arrow keys? What about function keys? A: Terminfo, some versions of termcap, and some versions of curses have support for these non-ASCII keys. Typically, a special key sends a multicharacter sequence (usually beginning with ESC, '\033'); parsing these can be tricky. (curses will do the parsing for you, if you call keypad() first.) Under MS-DOS, if you receive a character with value 0 (*not* '0'!) while reading the keyboard, it's a flag indicating that the next character read will be a code indicating a special key. See any DOS programming guide for lists of keyboard scan codes. (Very briefly: the up, left, right, and down arrow keys are 72, 75, 77, and 80, and the function keys are 59 through 68.) References: PCS Sec. 5.1.4 pp. 56-7. 19.6: How do I read the mouse? A: Consult your system documentation, or ask on an appropriate system-specific newsgroup (but check its FAQ list first). Mouse handling is completely different under the X window system, MS- DOS, the Macintosh, and probably every other system. References: PCS Sec. 5.5 pp. 78-80. 19.7: How can I do serial ("comm") port I/O? A: It's system-dependent. Under Unix, you typically open, read, and write a device file in /dev, and use the facilities of the terminal driver to adjust its characteristics. (See also questions 19.1 and 19.2.) Under MS-DOS, you can use the predefined stream stdaux, or a special file like COM1, or some primitive BIOS interrupts, or (if you require decent performance) any number of interrupt-driven serial I/O packages. Several netters recommend the book _C Programmer's Guide to Serial Communications_, by Joe Campbell. 19.8: How can I direct output to the printer? A: Under Unix, either use popen() (see question 19.30) to write to the lp or lpr program, or perhaps open a special file like /dev/lp. Under MS-DOS, write to the (nonstandard) predefined stdio stream stdprn, or open the special files PRN or LPT1. References: PCS Sec. 5.3 pp. 72-74. 19.9: How do I send escape sequences to control a terminal or other device? A: If you can figure out how to send characters to the device at all (see question 19.8 above), it's easy enough to send escape sequences. In ASCII, the ESC code is 033 (27 decimal), so code like fprintf(ofd, "\033[J"); sends the sequence ESC [ J . 19.10: How can I do graphics? A: Once upon a time, Unix had a fairly nice little set of device- independent plot functions described in plot(3) and plot(5). The GNU libplot package maintains the same spirit and supports many modern plot devices; see http://www.gnu.org/software/plotutils/plotutils.html . If you're programming for MS-DOS, you'll probably want to use libraries conforming to the VESA or BGI standards. If you're trying to talk to a particular plotter, making it draw is usually a matter of sending it the appropriate escape sequences; see also question 19.9. The vendor may supply a C- callable library, or you may be able to find one on the net. If you're programming for a particular window system (Macintosh, X windows, Microsoft Windows), you will use its facilities; see the relevant documentation or newsgroup or FAQ list. References: PCS Sec. 5.4 pp. 75-77. 19.11: How can I check whether a file exists? I want to warn the user if a requested input file is missing. A: It's surprisingly difficult to make this determination reliably and portably. Any test you make can be invalidated if the file is created or deleted (i.e. by some other process) between the time you make the test and the time you try to open the file. Three possible test functions are stat(), access(), and fopen(). (To make an approximate test using fopen(), just open for reading and close immediately, although failure does not necessarily indicate nonexistence.) Of these, only fopen() is widely portable, and access(), where it exists, must be used carefully if the program uses the Unix set-UID feature. Rather than trying to predict in advance whether an operation such as opening a file will succeed, it's often better to try it, check the return value, and complain if it fails. (Obviously, this approach won't work if you're trying to avoid overwriting an existing file, unless you've got something like the O_EXCL file opening option available, which does just what you want in this case.) References: PCS Sec. 12 pp. 189,213; POSIX Sec. 5.3.1, Sec. 5.6.2, Sec. 5.6.3. 19.12: How can I find out the size of a file, prior to reading it in? A: If the "size of a file" is the number of characters you'll be able to read from it in C, it is difficult or impossible to determine this number exactly. Under Unix, the stat() call will give you an exact answer. Several other systems supply a Unix-like stat() which will give an approximate answer. You can fseek() to the end and then use ftell(), or maybe try fstat(), but these tend to have the same sorts of problems: fstat() is not portable, and generally tells you the same thing stat() tells you; ftell() is not guaranteed to return a byte count except for binary files. Some systems provide functions called filesize() or filelength(), but these are obviously not portable, either. Are you sure you have to determine the file's size in advance? Since the most accurate way of determining the size of a file as a C program will see it is to open the file and read it, perhaps you can rearrange the code to learn the size as it reads. References: ISO Sec. <IP_ADDRESS>; H&S Sec. 15.5.1; PCS Sec. 12 p. 213; POSIX Sec. 5.6.2. 19.12b: How can I find the modification date and time of a file? A: The Unix and POSIX function is stat(), which several other systems supply as well. (See also question 19.12.) 19.13: How can a file be shortened in-place without completely clearing or rewriting it? A: BSD systems provide ftruncate(), several others supply chsize(), and a few may provide a (possibly undocumented) fcntl option F_FREESP. Under MS-DOS, you can sometimes use write(fd, "", 0). However, there is no portable solution, nor a way to delete blocks at the beginning. See also question 19.14. 19.14: How can I insert or delete a line (or record) in the middle of a file? A: Short of rewriting the file, you probably can't. The usual solution is simply to rewrite the file. (Instead of deleting records, you might consider simply marking them as deleted, to avoid rewriting.) Another possibility, of course, is to use a database instead of a flat file. See also questions 12.30 and 19.13. 19.15: How can I recover the file name given an open stream or file descriptor? A: This problem is, in general, insoluble. Under Unix, for instance, a scan of the entire disk (perhaps involving special permissions) would theoretically be required, and would fail if the descriptor were connected to 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 files yourself as you open them (perhaps with a wrapper function around fopen()). 19.16: How can I delete a file? A: The Standard C Library function is remove(). (This is therefore one of the few questions in this section for which the answer is *not* "It's system-dependent.") On older, pre-ANSI Unix systems, remove() may not exist, in which case you can try unlink(). References: K&R2 Sec. B1.1 p. 242; ISO Sec. <IP_ADDRESS>; H&S Sec. 15.15 p. 382; PCS Sec. 12 pp. 208,220-221; POSIX Sec. 5.5.1, Sec. 8.2.4. 19.16b: How do I copy files? A: Either use system() to invoke your operating system's copy utility (see question 19.27), or open the source and destination files (using fopen() or some lower-level file-opening system call), read characters or blocks of characters from the source file, and write them to the destination file. References: K&R Sec. 1, Sec. 7. 19.17: Why can't I open a file by its explicit path? The call fopen("c:\newdir\file.dat", "r") is failing. A: The file you actually requested -- with the characters \n and \f in its name -- probably doesn't exist, and isn't what you thought you were trying to open. In character constants and string literals, the backslash \ is an escape character, giving special meaning to the character following it. In order for literal backslashes in a pathname to be passed through to fopen() (or any other function) correctly, they have to be doubled, so that the first backslash in each pair quotes the second one: fopen("c:\\newdir\\file.dat", "r") Alternatively, under MS-DOS, it turns out that forward slashes are also accepted as directory separators, so you could use fopen("c:/newdir/file.dat", "r") (Note, by the way, that header file names mentioned in preprocessor #include directives are *not* string literals, so you may not have to worry about backslashes there.) 19.18: I'm getting an error, "Too many open files". How can I increase the allowable number of simultaneously open files? A: There are typically at least two resource limitations on the number of simultaneously open files: the number of low-level "file descriptors" or "file handles" available in the operating system, and the number of FILE structures available in the stdio library. Both must be sufficient. Under MS-DOS systems, you can control the number of operating system file handles with a line in CONFIG.SYS. Some compilers come with instructions (and perhaps a source file or two) for increasing the number of stdio FILE structures. 19.20: How can I read a directory in a C program? A: See if you can use the opendir() and readdir() functions, which are part of the POSIX standard and are available on most Unix variants. Implementations also exist for MS-DOS, VMS, and other systems. (MS-DOS also has FINDFIRST and FINDNEXT routines which do essentially the same thing.) readdir() only returns file names; if you need more information about the file, try calling stat(). To match filenames to some wildcard pattern, see question 13.7. References: K&R2 Sec. 8.6 pp. 179-184; PCS Sec. 13 pp. 230-1; POSIX Sec. 5.1; Schumacher, ed., _Software Solutions in C_ Sec. 8. 19.22: How can I find out how much memory is available? A: Your operating system may provide a routine which returns this information, but it's quite system-dependent. 19.23: How can I allocate arrays or structures bigger than 64K? A: A reasonable computer ought to give you transparent access to all available memory. If you're not so lucky, you'll either have to rethink your program's use of memory, or use various system-specific techniques. 64K is (still) a pretty big chunk of memory. No matter how much memory your computer has available, it's asking a lot to be able to allocate huge amounts of it contiguously. (The C Standard does not guarantee that single objects can be 32K or larger, or 64K for C9X.) Often it's a good idea to use data structures which don't require that all memory be contiguous. For dynamically-allocated multidimensional arrays, you can use pointers to pointers, as illustrated in question 6.16. Instead of a large array of structures, you can use a linked list, or an array of pointers to structures. If you're using a PC-compatible (8086-based) system, and running up against a 64K or 640K limit, consider using "huge" memory model, or expanded or extended memory, or malloc variants such as halloc() or farmalloc(), or a 32-bit "flat" compiler (e.g. djgpp, see question 18.3), or some kind of a DOS extender, or another operating system. References: ISO Sec. <IP_ADDRESS>; C9X Sec. <IP_ADDRESS>. 19.24: What does the error message "DGROUP data allocation exceeds 64K" mean, and what can I do about it? I thought that using large model meant that I could use more than 64K of data! A: Even in large memory models, MS-DOS compilers apparently toss certain data (strings, some initialized global or static variables) into a default data segment, and it's this segment that is overflowing. Either use less global data, or, if you're already limiting yourself to reasonable amounts (and if the problem is due to something like the number of strings), you may be able to coax the compiler into not using the default data segment for so much. Some compilers place only "small" data objects in the default data segment, and give you a way (e.g. the /Gt option under Microsoft compilers) to configure the threshold for "small." 19.25: How can I access memory (a memory-mapped device, or graphics memory) located at a certain address? A: Set a pointer, of the appropriate type, to the right number (using an explicit cast to assure the compiler that you really do intend this nonportable conversion): unsigned int *magicloc = (unsigned int *)0x12345678; Then, *magicloc refers to the location you want. (Under MS-DOS, you may find a macro like MK_FP() handy for working with segments and offsets.) References: K&R1 Sec. A14.4 p. 210; K&R2 Sec. A6.6 p. 199; ISO Sec. 6.3.4; Rationale Sec. 3.3.4; H&S Sec. 6.2.7 pp. 171-2. 19.27: How can I invoke another program (a standalone executable, or an operating system command) from within a C program? A: Use the library function system(), which does exactly that. Note that system's return value is at best the command's exit status (although even that is not guaranteed), and usually has nothing to do with the output of the command. Note also that system() accepts a single string representing the command to be invoked; if you need to build up a complex command line, you can use sprintf(). See also question 19.30. References: K&R1 Sec. 7.9 p. 157; K&R2 Sec. 7.8.4 p. 167, Sec. B6 p. 253; ISO Sec. <IP_ADDRESS>; H&S Sec. 19.2 p. 407; PCS Sec. 11 p. 179. 19.30: How can I invoke another program or command and trap its output? A: Unix and some other systems provide a popen() function, which sets up a stdio stream on a pipe connected to the process running a command, so that the output can be read (or the input supplied). (Also, remember to call pclose().) If you can't use popen(), you may be able to use system(), with the output going to a file which you then open and read. If you're using Unix and popen() isn't sufficient, you can learn about pipe(), dup(), fork(), and exec(). (One thing that probably would *not* work, by the way, would be to use freopen().) References: PCS Sec. 11 p. 169. 19.31: How can my program discover the complete pathname to the executable 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 solution. References: K&R1 Sec. 5.11 p. 111; K&R2 Sec. 5.10 p. 115; ISO Sec. <IP_ADDRESS>.1; H&S Sec. 20.1 p. 416. 19.32: How can I automatically locate a program's configuration files in the same directory as the executable? A: It's hard; see also question 19.31 above. Even if you can figure out a workable way to do it, you might want to consider making the program's auxiliary (library) directory configurable, perhaps with an environment variable. (It's especially important to allow variable placement of a program's configuration files when the program will be used by several people, e.g. on a multiuser system.) 19.33: How can a process change an environment variable in its caller? A: It may or may not be possible to do so at all. Different operating systems implement global 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() or putenv() functions for the purpose), and the modified environment is generally passed on to child processes, but it is *not* propagated back to the parent process. Under MS-DOS, it's possible to manipulate the master copy of the environment, but the required techniques are arcane. (See an MS-DOS FAQ list.) 19.36: How can I read in an object file and jump to locations in it? A: You want a dynamic linker or loader. It may be possible to malloc some space and read in object files, but you have to know an awful lot about object file formats, relocation, etc. Under BSD Unix, you could use system() and ld -A to do the linking for you. Many versions of SunOS and System V have the -ldl library which allows object files to be dynamically loaded. Under VMS, use LIB$FIND_IMAGE_SYMBOL. GNU has a package called "dld". See also question 15.13. 19.37: How can I implement a delay, or time a user's response, with sub- second resolution? A: Unfortunately, there is no portable way. V7 Unix, and derived systems, provided a fairly useful ftime() function with resolution up to a millisecond, but it has disappeared from System V and POSIX. Other routines you might look for on your system include clock(), delay(), gettimeofday(), msleep(), nap(), napms(), nanosleep(), setitimer(), sleep(), times(), and usleep(). (A function called wait(), however, is at least under Unix *not* what you want.) The select() and poll() calls (if available) can be pressed into service to implement simple delays. On MS-DOS machines, it is possible to reprogram the system timer and timer interrupts. Of these, only clock() is part of the ANSI Standard. The difference between two calls to clock() gives elapsed execution time, and may even have subsecond resolution, if CLOCKS_PER_SEC is greater than 1. However, clock() gives elapsed processor time used by the current program, which on a multitasking system may differ considerably from real time. If you're trying to implement a delay and all you have available is a time-reporting function, you can implement a CPU-intensive busy-wait, but this is only an option on a single-user, single- tasking machine as it is terribly antisocial to any other processes. Under a multitasking operating system, be sure to use a call which puts your process to sleep for the duration, such as sleep() or select(), or pause() in conjunction with alarm() or setitimer(). For really brief delays, it's tempting to use a do-nothing loop like long int i; for(i = 0; i < 1000000; i++) ; but resist this temptation if at all possible! For one thing, your carefully-calculated delay loops will stop working properly next month when a faster processor comes out. Perhaps worse, a clever compiler may notice that the loop does nothing and optimize it away completely. References: H&S Sec. 18.1 pp. 398-9; PCS Sec. 12 pp. 197-8,215- 6; POSIX Sec. 4.5.2. 19.38: How can I trap or ignore keyboard interrupts like control-C? A: The basic step is to call signal(), either as #include <signal.h> signal(SIGINT, SIG_IGN); to ignore the interrupt signal, or as extern void func(int); signal(SIGINT, func); to cause control to transfer to function func() on receipt of an interrupt signal. On a multi-tasking system such as Unix, it's best to use a slightly more involved technique: extern void func(int); if(signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, func); The test and extra call ensure that a keyboard interrupt typed in the foreground won't inadvertently interrupt a program running in the background (and it doesn't hurt to code calls to signal() this way on any system). On some systems, keyboard interrupt handling is also a function of the mode of the terminal-input subsystem; see question 19.1. On some systems, checking for keyboard interrupts is only performed when the program is reading input, and keyboard interrupt handling may therefore depend on which input routines are being called (and *whether* any input routines are active at all). On MS-DOS systems, setcbrk() or ctrlbrk() functions may also be involved. References: ISO Secs. 7.7,7.7.1; H&S Sec. 19.6 pp. 411-3; PCS Sec. 12 pp. 210-2; POSIX Secs. 3.3.1,3.3.4. 19.39: How can I handle floating-point exceptions gracefully? A: On many systems, you can define a function matherr() which will be called when there are certain floating-point errors, such as errors in the math routines in <math.h>. You may also be able to use signal() (see question 19.38 above) to catch SIGFPE. See also question 14.9. References: Rationale Sec. 4.5.1. 19.40: How do I... Use sockets? Do networking? Write client/server applications? A: All of these questions are outside of the scope of this list and have much more to do with the networking facilities which you have available than they do with C. Good books on the subject are Douglas Comer's three-volume _Internetworking with TCP/IP_ and W. R. Stevens's _UNIX Network Programming_. (There is also plenty of information out on the net itself, including the "Unix Socket FAQ" at http://kipper.york.ac.uk/~vic/sock-faq/ .) 19.40b: How do I... Use BIOS calls? Write ISR's? Create TSR's? A: These are very particular to specific systems (PC compatibles running MS-DOS, most likely). You'll get much better information in a specific newsgroup such as comp.os.msdos.programmer or its FAQ list; another excellent resource is Ralf Brown's interrupt list. 19.40c: I'm trying to compile this program, but the compiler is complaining that "union REGS" is undefined, and the linker is complaining that int86() is undefined. A: Those have to do with MS-DOS interrupt programming. They don't exist on other systems. 19.41: But I can't use all these nonstandard, system-dependent functions, because my program has to be ANSI compatible! A: You're out of luck. Either you misunderstood your requirement, or it's an impossible one to meet. ANSI/ISO Standard C simply does not define ways of doing these things; it is a language standard, not an operating system standard. An international standard which does address many of these issues is POSIX (IEEE 1003.1, ISO/IEC 9945-1), and many operating systems (not just Unix) now have POSIX-compatible programming interfaces. It is possible, and desirable, for *most* of a program to be ANSI-compatible, deferring the system-dependent functionality to a few routines in a few files which are rewritten for each system ported to. Section 20. Miscellaneous 20.1: How can I return multiple values from a function? A: Either pass pointers to several locations which the function can fill in, or have the function return a structure containing the desired values, or (in a pinch) consider global variables. See also questions 2.7, 4.8, and 7.5a. 20.3: How do I access command-line arguments? A: They are pointed to by the argv array with which main() is called. See also questions 8.2, 13.7, and 19.20. References: K&R1 Sec. 5.11 pp. 110-114; K&R2 Sec. 5.10 pp. 114- 118; ISO Sec. <IP_ADDRESS>.1; H&S Sec. 20.1 p. 416; PCS Sec. 5.6 pp. 81-2, Sec. 11 p. 159, pp. 339-40 Appendix F; Schumacher, ed., _Software Solutions in C_ Sec. 4 pp. 75-85. 20.5: 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 most portable 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 interchange them easily between machines, and 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 (RFC 1014), OSI's ASN.1 (referenced in CCITT X.409 and ISO 8825 "Basic Encoding Rules"), CDF, netCDF, or HDF. See also questions 2.12 and 12.38. References: PCS Sec. 6 pp. 86, 88. 20.6: If I have a char * variable pointing to the name of a function, how can I call that function? A: The most straightforward thing to do is to maintain a correspondence table of names and function pointers: int func(), anotherfunc(); struct { char *name; int (*funcptr)(); } symtab[] = { "func", func, "anotherfunc", anotherfunc, }; Then, search the table for the name, and call via the associated function pointer. See also questions 2.15, 18.14, and 19.36. References: PCS Sec. 11 p. 168. 20.8: How can I implement sets or arrays of bits? A: Use arrays of char or int, with a few macros to access the desired bit at the proper index. Here are some simple macros to use with arrays of char: #include <limits.h> /* for CHAR_BIT */ #define BITMASK(b) (1 << ((b) % CHAR_BIT)) #define BITSLOT(b) ((b) / CHAR_BIT) #define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b)) #define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b)) (If you don't have <limits.h>, try using 8 for CHAR_BIT.) References: H&S Sec. 7.6.7 pp. 211-216. 20.9: How can I determine whether a machine's byte order is big-endian or little-endian? A: One way is to use a pointer: int x = 1; if(*(char *)&x == 1) printf("little-endian\n"); else printf("big-endian\n"); It's also possible to use a union. See also question 10.16. References: H&S Sec. 6.1.2 pp. 163-4. 20.10: How can I convert integers to binary or hexadecimal? A: Make sure you really know what you're asking. Integers are stored internally in binary, although for most purposes it is not incorrect to think of them as being in octal, decimal, or hexadecimal, whichever is convenient. The base in which a number is expressed matters only when that number is read in from or written out to the outside world. In source code, a non-decimal base is indicated by a leading 0 or 0x (for octal or hexadecimal, respectively). During I/O, the base of a formatted number is controlled in the printf and scanf family of functions by the choice of format specifier (%d, %o, %x, etc.) and in the strtol() and strtoul() functions by the third argument. If you need to output numeric strings in arbitrary bases, you'll have to supply your own function to do so (it will essentially be the inverse of strtol). During *binary* I/O, however, the base again becomes immaterial. For more information about "binary" I/O, see question 2.11. See also questions 8.6 and 13.1. References: ISO Secs. <IP_ADDRESS>,<IP_ADDRESS>. 20.11: Can I use base-2 constants (something like 0b101010)? Is there a printf() format for binary? A: No, on both counts. You can convert base-2 string representations to integers with strtol(). See also question 20.10. 20.12: What is the most efficient way to count the number of bits which are set in an integer? A: Many "bit-fiddling" problems like this one can be sped up and streamlined using lookup tables (but see question 20.13 below). 20.13: What's the best way of making my program efficient? A: By picking good algorithms, implementing them carefully, and making sure that your program isn't doing any extra work. For example, the most microoptimized character-copying loop in the world will be beat by code which avoids having to copy characters at all. When worrying about efficiency, it's important to keep several things in perspective. First of all, although efficiency is an enormously popular topic, it is not always as important 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 usually 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 seemingly "inefficient" code may be quite efficiently compilable, and 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 caching techniques. Even for code that *is* time-critical, one of the least effective optimization techniques is to fuss with 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 actually degraded, and are rarely portable (i.e. they may speed things up on one machine but slow them down on another). In any case, tweaking the coding usually results in at best linear performance improvements; the big payoffs are in better algorithms. For more discussion of efficiency tradeoffs, as well as good advice on how to improve efficiency when it is important, see chapter 7 of Kernighan and Plauger's _The Elements of Programming Style_, and Jon Bentley's _Writing Efficient Programs_. 20.14: Are pointers really faster than arrays? How much do function calls 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 compiler, not a keystroke-programmable calculator. Any decent 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. (See also question 3.12.) 20.15b: People claim that optimizing compilers are good and that we no longer have to write things in assembler for speed, but my compiler can't even replace i/=2 with a shift. A: Was i signed or unsigned? If it was signed, a shift is not equivalent (hint: think about the result if i is negative and odd), so the compiler was correct not to use it. 20.15c: How can I swap two values without using a temporary? A: The standard hoary old assembly language programmer's trick is: a ^= b; b ^= a; a ^= b; But this sort of code has little place in modern, HLL programming. Temporary variables are essentially free, and the idiomatic code using three assignments, namely int t = a; a = b; b = t; is not only clearer to the human reader, it is more likely to be recognized by the compiler and turned into the most-efficient code (e.g. using a swap instruction, if available). The latter code is obviously also amenable to use with pointers and floating-point values, unlike the XOR trick. See also questions 3.3b and 10.3. 20.17: Is there a way to switch on strings? A: Not directly. Sometimes, it's appropriate to use a separate function to map strings to integer codes, and then switch on those. Otherwise, of course, you can fall back on strcmp() and a conventional if/else chain. See also questions 10.12, 20.18, and 20.29. References: K&R1 Sec. 3.4 p. 55; K&R2 Sec. 3.4 p. 58; ISO Sec. <IP_ADDRESS>; H&S Sec. 8.7 p. 248. 20.18: Is there a way to have non-constant case labels (i.e. ranges or arbitrary expressions)? A: No. The switch statement was originally designed to be quite simple for the compiler to translate, therefore case labels are limited to single, constant, integral expressions. You *can* attach several case labels to the same statement, which will let you cover a small range if you don't mind listing all cases explicitly. If you want to select on arbitrary ranges or non-constant expressions, you'll have to use an if/else chain. See also question 20.17. References: K&R1 Sec. 3.4 p. 55; K&R2 Sec. 3.4 p. 58; ISO Sec. <IP_ADDRESS>; Rationale Sec. <IP_ADDRESS>; H&S Sec. 8.7 p. 248. 20.19: Are the outer parentheses in return statements really optional? A: Yes. Long ago, in the early days of C, they were required, and just enough people learned C then, and wrote code which is still in circulation, that the notion that they might still be required is widespread. (As it happens, parentheses are optional with the sizeof operator, too, under certain circumstances.) References: K&R1 Sec. A18.3 p. 218; ISO Sec. 6.3.3, Sec. 6.6.6; H&S Sec. 8.9 p. 254. 20.20: Why don't C comments nest? How am I supposed to comment out code containing comments? Are comments legal inside quoted strings? A: C comments don't nest mostly because PL/I's comments, which C's are borrowed from, don't either. Therefore, it is usually better to "comment out" large sections of code, which might contain comments, with #ifdef or #if 0 (but see question 11.19). 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. Note also that // comments, as in C++, are not yet legal in C, so it's not a good idea to use them in C programs (even if your compiler supports them as an extension). References: K&R1 Sec. A2.1 p. 179; K&R2 Sec. A2.2 p. 192; ISO Sec. 6.1.9, Annex F; Rationale Sec. 3.1.9; H&S Sec. 2.2 pp. 18- 9; PCS Sec. 10 p. 130. 20.20b: Is C a great language, or what? Where else could you write something like a+++++b ? A: Well, you can't meaningfully write it in C, either. The rule for lexical analysis is that at each point during a straightforward left-to-right scan, the longest possible token is determined, without regard to whether the resulting sequence of tokens makes sense. The fragment in the question is therefore interpreted as a ++ ++ + b and cannot be parsed as a valid expression. References: K&R1 Sec. A2 p. 179; K&R2 Sec. A2.1 p. 192; ISO Sec. 6.1; H&S Sec. 2.3 pp. 19-20. 20.24: Why doesn't C have nested functions? A: It's not trivial to implement nested functions such that they have the proper access to local variables in the containing function(s), so they were deliberately left out of C as a simplification. (gcc does allow them, as an extension.) For many potential uses of nested functions (e.g. qsort comparison functions), an adequate if slightly cumbersome solution is to use an adjacent function with static declaration, communicating if necessary via a few static variables. (A cleaner solution, though unsupported by qsort(), is to pass around a pointer to a structure containing the necessary context.) 20.24b: What is assert() and when would I use it? A: It is a macro, defined in <assert.h>, for testing "assertions". An assertion essentially documents an assumption being made by the programmer, an assumption which, if violated, would indicate a serious programming error. For example, a function which was supposed to be called with a non-null pointer could write assert(p != NULL); A failed assertion terminates the program. Assertions should *not* be used to catch expected errors, such as malloc() or fopen() failures. References: K&R2 Sec. B6 pp. 253-4; ISO Sec. 7.2; H&S Sec. 19.1 p. 406. 20.25: How can I call FORTRAN (C++, 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. More information may be found in FORT.gz by Glenn Geers, available via anonymous ftp from suphys.physics.su.oz.au in the src directory. cfortran.h, a C header file, simplifies C/FORTRAN interfacing on many popular machines. It is available via anonymous ftp from zebra.desy.de or at http://www-zeus.desy.de/~burow . In C++, a "C" modifier in an external function declaration indicates that the function is to be called using C calling conventions. References: H&S Sec. 4.9.8 pp. 106-7. 20.26: Does anyone know of a program for converting Pascal or FORTRAN (or LISP, Ada, awk, "Old" C, ...) to C? A: Several freely distributable programs are available: p2c A Pascal to C converter written by Dave Gillespie, posted to comp.sources.unix in March, 1990 (Volume 21); also available by anonymous ftp from csvax.cs.caltech.edu, file pub/p2c-1.20.tar.Z . ptoc Another Pascal to C converter, this one written in Pascal (comp.sources.unix, Volume 10, also patches in Volume 13?). f2c A FORTRAN to C converter jointly developed by people from Bell Labs, Bellcore, and Carnegie Mellon. To find out more about f2c, send the mail message "send index from f2c" to<EMAIL_ADDRESS>or research!netlib. (It is also available via anonymous ftp on netlib.att.com, in directory netlib/f2c.) This FAQ list's maintainer also has available a list of a few other commercial translation products, and some for more obscure languages. See also questions 11.31 and 18.16. 20.27: Is C++ a superset of C? Can I use a C++ compiler to compile C code? A: C++ was derived from C, and is largely based on it, but there are some legal C constructs which are not legal C++. Conversely, ANSI C inherited several features from C++, including prototypes and const, so neither language is really a subset or superset of the other; the two also define the meaning of some common constructs differently. In spite of the differences, many C programs will compile correctly in a C++ environment, and many recent compilers offer both C and C++ compilation modes. See also questions 8.9 and 20.20. References: H&S p. xviii, Sec. 1.1.5 p. 6, Sec. 2.8 pp. 36-7, Sec. 4.9 pp. 104-107. 20.28: I need a sort of an "approximate" strcmp routine, for comparing two strings for close, but not necessarily exact, equality. A: Some nice information and algorithms having to do with approximate string matching, as well as a useful bibliography, can be found in Sun Wu and Udi Manber's paper "AGREP -- A Fast Approximate Pattern-Matching Tool." Another approach involves the "soundex" algorithm, which maps similar-sounding words to the same codes. Soundex was designed for discovering similar-sounding names (for telephone directory assistance, as it happens), but it can be pressed into service for processing arbitrary words. References: Knuth Sec. 6 pp. 391-2 Volume 3; Wu and Manber, "AGREP -- A Fast Approximate Pattern-Matching Tool" . 20.29: What is hashing? A: Hashing is the process of mapping strings to integers, usually in a relatively small range. A "hash function" maps a string (or some other data structure) to a bounded number (the "hash bucket") which can more easily be used as an index in an array, or for performing repeated comparisons. (Obviously, a mapping from a potentially huge set of strings to a small set of integers will not be unique. Any algorithm using hashing therefore has to deal with the possibility of "collisions.") Many hashing functions and related algorithms have been developed; a full treatment is beyond the scope of this list. References: K&R2 Sec. 6.6; Knuth Sec. 6.4 pp. 506-549 Volume 3; Sedgewick Sec. 16 pp. 231-244. 20.31: How can I find the day of the week given the date? A: Use mktime() or localtime() (see questions 13.13 and 13.14, but beware of DST adjustments if tm_hour is 0), or Zeller's congruence (see the sci.math FAQ list), or this elegant code by Tomohiko Sakamoto: int dayofweek(int y, int m, int d) /* 0 = Sunday */ { static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; y -= m < 3; return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7; } See also questions 13.14 and 20.32. References: ISO Sec. <IP_ADDRESS>. 20.32: Will 2000 be a leap year? Is (year % 4 == 0) an accurate test for leap years? A: Yes and no, respectively. The full expression for the present Gregorian calendar is year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) See a good astronomical almanac or other reference for details. (To forestall an eternal debate: references which claim the existence of a 4000-year rule are wrong.) See also questions 13.14 and 13.14b. 20.34: Here's a good puzzle: how do you write a program which produces its own source code as output? A: It is actually quite difficult to write a self-reproducing program that is truly portable, due particularly to quoting and character set difficulties. Here is a classic example (which ought to be presented on one line, although it will fix itself the first time it's run): char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}"; main(){printf(s,34,s,34);} (This program, like many of the genre, neglects to #include <stdio.h>, and assumes that the double-quote character " has the value 34, as it does in ASCII.) 20.35: What is "Duff's Device"? A: It's a devastatingly deviously unrolled byte-copying loop, devised by Tom Duff while he was at Lucasfilm. In its "classic" form, it looks like: register n = (count + 7) / 8; /* count > 0 assumed */ switch (count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while (--n > 0); } where count bytes are to be copied from the array pointed to by from to the memory location pointed to by to (which is a memory- mapped device output register, which is why to isn't incremented). It solves the problem of handling the leftover bytes (when count isn't a multiple of 8) by interleaving a switch statement with the loop which copies bytes 8 at a time. (Believe it or not, it *is* legal to have case labels buried within blocks nested in a switch statement like this. In his announcement of the technique to C's developers and the world, Duff noted that C's switch syntax, in particular its "fall through" behavior, had long been controversial, and that "This code forms some sort of argument in that debate, but I'm not sure whether it's for or against.") 20.36: When will the next International Obfuscated C Code Contest (IOCCC) be held? How can I get a copy of the current and previous winning entries? A: The contest is in a state of flux; see http://www.ioccc.org/index.html for current details. Contest winners are usually announced at a Usenix conference, and are posted to the net sometime thereafter. Winning entries from previous years (back to 1984) are archived at ftp.uu.net (see question 18.16) under the directory pub/ioccc/; see also http://www.ioccc.org/index.html . 20.37: What was the entry keyword mentioned in K&R1? A: It was reserved to allow the possibility of having functions with multiple, differently-named entry points, a la FORTRAN. It was not, to anyone's knowledge, ever implemented (nor does anyone remember what sort of syntax might have been imagined for it). It has been withdrawn, and is not a keyword in ANSI C. (See also question 1.12.) References: K&R2 p. 259 Appendix C. 20.38: Where does the name "C" come from, anyway? A: C was derived from Ken Thompson's experimental language B, which was inspired by Martin Richards's BCPL (Basic Combined Programming Language), which was a simplification of CPL (Cambridge Programming Language). For a while, there was speculation that C's successor might be named P (the third letter in BCPL) instead of D, but of course the most visible descendant language today is C++. 20.39: How do you pronounce "char"? A: You can pronounce the C keyword "char" in at least three ways: like the English words "char," "care," or "car" (or maybe even "character"); the choice is arbitrary. 20.39b: What do "lvalue" and "rvalue" mean? A: Simply speaking, an "lvalue" is an expression that could appear on the left-hand sign of an assignment; you can also think of it as denoting an object that has a location. (But see question 6.7 concerning arrays.) An "rvalue" is any expression that has a value (and that can therefore appear on the right-hand sign of an assignment). 20.40: Where can I get extra copies of this list? What about back issues? A: An up-to-date copy may be obtained from ftp.eskimo.com in directory u/s/scs/C-faq/. You can also just pull it off the net; it is normally posted to comp.lang.c on the first of each month, with an Expires: line which should keep it around all month. A parallel, abridged version is available (and posted), as is a list of changes accompanying each significantly updated version. The various versions of this list are also posted to the newsgroups comp.answers and news.answers . Several sites archive news.answers postings and other FAQ lists, including this one; two sites are rtfm.mit.edu (directories pub/usenet/news.answers/C-faq/ and pub/usenet/comp.lang.c/) and ftp.uu.net (directory usenet/news.answers/C-faq/). If you don't have ftp access, a mailserver at rtfm.mit.edu can mail you FAQ lists: send a message containing the single word "help" to<EMAIL_ADDRESS>. See the meta-FAQ list in news.answers for more information. A hypertext (HTML) version of this FAQ list is available on the World-Wide Web; the URL is http://www.eskimo.com/~scs/C-faq/top.html . A comprehensive site which references all Usenet FAQ lists is http://www.faqs.org/faqs/ . An extended version of this FAQ list has been published by Addison-Wesley as _C Programming FAQs: Frequently Asked Questions_ (ISBN 0-201-84519-9). An errata list is at http://www.eskimo.com/~scs/C-faq/book/Errata.html and on ftp.eskimo.com in u/s/scs/ftp/C-faq/book/Errata . This list is an evolving document containing questions which have been Frequent since before the Great Renaming; it is 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 American National Standards Institute, _American National Standard for Information Systems -- Programming Language -- C_, ANSI X3.159-1989 (see question 11.2). [ANSI] American National Standards Institute, _Rationale for American National Standard for Information Systems -- Programming Language -- C_ (see question 11.2). [Rationale] Jon Bentley, _Writing Efficient Programs_, Prentice-Hall, 1982, ISBN 0-13-970244-X. David Burki, "Date Conversions," _The C Users Journal_, February 1993, pp. 29-34. Ian F. Darwin, _Checking C Programs with lint_, O'Reilly, 1988, ISBN 0-937175-30-7. David Goldberg, "What Every Computer Scientist Should Know about Floating-Point Arithmetic," _ACM Computing Surveys_, Vol. 23 #1, March, 1991, pp. 5