Sunteți pe pagina 1din 604

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.

com

This article is Copyright 1990-1996 by Steve Summit. Content from the book _C Programming FAQs: Frequently Asked Questions_ is made available here by permission of the author and the publisher as a service to the community. It is intended to complement the use of the published text and is protected by international copyright laws. The content is made available here and may be accessed freely for personal use but may not be republished without permission. Certain topics come up again and again on this newsgroup. They are good questions, and the answers may not be immediately obvious, but each time they recur, much net bandwidth and reader time is wasted on repetitive responses, and on tedious corrections to the incorrect answers which are inevitably posted. This article, which is posted monthly, attempts to answer these common questions definitively and succinctly, so that net discussion can move on to more constructive topics without continual regression to first principles. No mere newsgroup article can substitute for thoughtful perusal of a full-length tutorial or language reference manual. Anyone interested enough in C to be following this newsgroup should also be interested enough to read and study one or more such manuals, preferably several times. Some C books and compiler manuals are unfortunately inadequate; a few even perpetuate some of the myths which this article attempts to refute. Several noteworthy books on C are listed in this article's bibliography; see also question 18.10. Many of the questions and answers are cross-referenced to these books, for further study by the interested and dedicated reader (but beware of ANSI vs. ISO C Standard section numbers; see question 11.1). If you have a question about C which is not answered in this article, first try to answer it by checking a few of the referenced books, or by asking knowledgeable colleagues, before posing your question to the net at large. There are many people on the net who are happy to answer questions, but the volume of repetitive answers posted to one question, as well as the growing number of questions as the net attracts more readers, can become oppressive. If you have questions or comments

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

prompted by this article, please reply by mail rather than following up -this article is meant to decrease net traffic, not increase it. Besides listing frequently-asked questions, this article also summarizes frequently-posted answers. Even if you know all the answers, it's worth skimming through this list once in a while, so that when you see one of its questions unwittingly posted, you won't have to waste time answering. This article was last modified on February 8, 1996, and its travels may have taken it far from its original home on Usenet. It may now be out-of-date, particularly if you are looking at a printed copy or one retrieved from a tertiary archive site or CD-ROM. You can always obtain the most up-to-date copy by anonymous ftp from sites ftp.eskimo.com, rtfm.mit.edu, or ftp.uu.net (see questions 18.16 and 20.40), or by sending the e-mail message "help" to mail-server@rtfm.mit.edu . Since this list is modified from time to time, its question numbers may not match those in older or newer copies which are in circulation; be careful when referring to FAQ list entries by number alone. This article was produced for free redistribution. to pay anyone for a copy of it. You should not need

Other versions of this document are also available. Posted along with it are an abridged version and (when there are changes) a list of differences with respect to the previous version. A hypertext version is available on the world-wide web (WWW); see URL . Finally, for those who might prefer a bound, hardcopy version (and even longer answers to even more questions!), a book-length version has been published by AddisonWesley (ISBN 0-201-84519-9). This article is always being improved. your comments to scs@eskimo.com . Your input is welcomed. Send

The questions answered here are divided into several categories: 1. Declarations and Initializations

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

Structures, Unions, and Enumerations Expressions Pointers Null Pointers Arrays and Pointers Memory Allocation Characters and Strings Boolean Expressions and Variables C Preprocessor ANSI/ISO Standard C Stdio Library Functions Floating Point Variable-Length Argument Lists Strange Problems Style Tools and Resources System Dependencies Miscellaneous

(The question numbers within each section are not continuous because they are aligned with the forthcoming book-length version, which contains even more questions.) Herewith, some frequently-asked questions and their answers:

Section 1. Declarations and Initializations 1.1: A: How do you decide which integer type to use? If you might need large values (above 32,767 or below -32,767), use long. Otherwise, if space is very important (i.e. if there are large arrays or many structures), use short. Otherwise, use int. If well-defined overflow characteristics are important and negative values are not, or if you want to steer clear of signextension problems when manipulating bits or bytes, use one of the corresponding unsigned types. (Beware when mixing signed

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

and unsigned values in expressions, though.) Although character types (especially unsigned char) can be used as "tiny" integers, doing so is sometimes more trouble than it's worth, due to unpredictable sign extension and increased code size. (Using unsigned char can help; see question 12.1 for a related problem.) A similar space/time tradeoff applies when deciding between float and double. None of the above rules apply if the address of a variable is taken and must have a particular type. If for some reason you need to declare something with an *exact* size (usually the only good reason for doing so is when attempting to conform to some externally-imposed storage layout, but see question 20.5), be sure to encapsulate the choice behind an appropriate typedef. References: K&R1 Sec. 2.2 p. 34; K&R2 Sec. 2.2 p. 36, Sec. A4.2 pp. 195-6, Sec. B11 p. 257; ANSI Sec. 2.2.4.2.1, Sec. 3.1.2.5; ISO Sec. 5.2.4.2.1, Sec. 6.1.2.5; H&S Secs. 5.1,5.2 pp. 110-114. 1.4: A: What should the 64-bit type on new, 64-bit machines be? Some vendors of C products for 64-bit machines support 64-bit long ints. Others fear that too much existing code is written to assume that ints and longs are the same size, or that one or the other of them is exactly 32 bits, and introduce a new, nonstandard, 64-bit long long (or __longlong) type instead. Programmers interested in writing portable code should therefore insulate their 64-bit type needs behind appropriate typedefs. Vendors who feel compelled to introduce a new, longer integral type should advertise it as being "at least 64 bits" (which is truly new, a type traditional C does not have), and not "exactly 64 bits." References: ANSI Sec. F.5.6; ISO Sec. G.5.6.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

1.7: A:

What's the best way to declare and define global variables? First, though there can be many "declarations" (and in many translation units) of a single "global" (strictly speaking, "external") variable or function, there must be exactly one "definition". (The definition is the declaration that actually allocates space, and provides an initialization value, if any.) The best arrangement is to place each definition in some relevant .c file, with an external declaration in a header (".h") file, which is #included wherever the declaration is needed. The .c file containing the definition should also #include the same header file, so that the compiler can check that the definition matches the declarations. This rule promotes a high degree of portability: it is consistent with the requirements of the ANSI C Standard, and is also consistent with most pre-ANSI compilers and linkers. (Unix compilers and linkers typically use a "common model" which allows multiple definitions, as long as at most one is initialized; this behavior is mentioned as a "common extension" by the ANSI Standard, no pun intended. A few very odd systems may require an explicit initializer to distinguish a definition from an external declaration.) It is possible to use preprocessor tricks to arrange that a line like DEFINE(int, i); need only be entered once in one header file, and turned into a definition or a declaration depending on the setting of some macro, but it's not clear if this is worth the trouble. It's especially important to put global declarations in header files if you want the compiler to catch inconsistent declarations for you. In particular, never place a prototype for an external function in a .c file: it wouldn't generally be

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

checked for consistency with the definition, and an incompatible prototype is worse than useless. See also questions 10.6 and 18.8. References: K&R1 Sec. 4.5 pp. 76-7; K&R2 Sec. 4.4 pp. 80-1; ANSI Sec. 3.1.2.2, Sec. 3.7, Sec. 3.7.2, Sec. F.5.11; ISO Sec. 6.1.2.2, Sec. 6.7, Sec. 6.7.2, Sec. G.5.11; Rationale Sec. 3.1.2.2; H&S Sec. 4.8 pp. 101-104, Sec. 9.2.3 p. 267; CT&P Sec. 4.2 pp. 54-56. 1.11: A: What does extern mean in a function declaration? It can be used as a stylistic hint to indicate that the function's definition is probably in another source file, but there is no formal difference between extern int f(); and int f(); References: ANSI Sec. 3.1.2.2, Sec. 3.5.1; ISO Sec. 6.1.2.2, Sec. 6.5.1; Rationale Sec. 3.1.2.2; H&S Secs. 4.3,4.3.1 pp. 756. 1.12: A: What's the auto keyword good for? Nothing; it's archaic. See also question 20.37.

References: K&R1 Sec. A8.1 p. 193; ANSI Sec. 3.1.2.4, Sec. 3.5.1; ISO Sec. 6.1.2.4, Sec. 6.5.1; H&S Sec. 4.3 p. 75, Sec. 4.3.1 p. 76. 1.14: I can't seem to define a linked list successfully. typedef struct { I tried

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

char *item; NODEPTR next; } *NODEPTR; but the compiler gave me error messages. contain a pointer to itself? A: Can't a structure in C

Structures in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. The problem with the NODEPTR example is that the typedef has not been defined at the point where the "next" field is declared. To fix this code, first give the structure a tag ("struct node"). Then, declare the "next" field as a simple "struct node *", or disentangle the typedef declaration from the structure definition, or both. One corrected version would be struct node { char *item; struct node *next; }; typedef struct node *NODEPTR; and there are at least three other equivalently correct ways of arranging it. A similar problem, with a similar solution, can arise when attempting to declare a pair of typedef'ed mutually referential structures. See also question 2.1. References: K&R1 Sec. 6.5 p. 101; K&R2 Sec. 6.5 p. 139; ANSI Sec. 3.5.2, Sec. 3.5.2.3, esp. examples; ISO Sec. 6.5.2, Sec. 6.5.2.3; H&S Sec. 5.6.1 pp. 132-3.

1.21:

How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

The first part of this question can be answered in at least three ways: 1. 2. char *(*(*a[N])())(); Build the declaration up incrementally, using typedefs: typedef char *pc; typedef pc fpc(); typedef fpc *pfpc; typedef pfpc fpfpc(); typedef fpfpc *pfpfpc; pfpfpc a[N]; 3. /* /* /* /* /* /* pointer to char */ function returning pointer to char */ pointer to above */ function returning... */ pointer to... */ array of... */

Use the cdecl program, which turns English into C and vice versa: cdecl> declare a as array of pointer to function returning pointer to function returning pointer to char char *(*(*a[])())() cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions, like the one above). Versions of cdecl are in volume 14 of comp.sources.unix (see question 18.16) and K&R2.

Any good book on C should explain how to read these complicated C declarations "inside out" to understand them ("declaration mimics use"). The pointer-to-function declarations in the examples above have not included parameter type information. When the parameters have complicated types, declarations can *really* get messy. (Modern versions of cdecl can help here, too.) References: K&R2 Sec. 5.12 p. 122; ANSI Sec. 3.5ff (esp.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Sec. 3.5.4); ISO Sec. 6.5ff (esp. Sec. 6.5.4); H&S Sec. 4.5 pp. 85-92, Sec. 5.10.1 pp. 149-50. 1.22: How can I declare a function that can return a pointer to a function of the same type? I'm building a state machine with one function for each state, each of which returns a pointer to the function for the next state. But I can't find a way to declare the functions. You can't quite do it directly. Either have the function return a generic function pointer, with some judicious casts to adjust the types as the pointers are passed around; or have it return a structure containing only a pointer to a function returning that structure. My compiler is complaining about an invalid redeclaration of a function, but I only define it once and call it once. Functions which are called without a declaration in scope (perhaps because the first call precedes the function's definition) are assumed to be declared as returning int (and without any argument type information), leading to discrepancies if the function is later declared or defined otherwise. Non-int functions must be declared before they are called. Another possible source of this problem is that the function has the same name as another one declared in some header file. See also questions 11.3 and 15.1. References: K&R1 Sec. 4.2 p. 70; K&R2 Sec. 4.2 p. 72; ANSI Sec. 3.3.2.2; ISO Sec. 6.3.2.2; H&S Sec. 4.7 p. 101. 1.30: What can I safely assume about the initial values of variables which are not explicitly initialized? If global variables start out as "zero," is that good enough for null pointers and floating-point zeroes?

A:

1.25:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Variables with "static" duration (that is, those declared outside of functions, and those declared with the storage class static), are guaranteed initialized (just once, at program startup) to zero, as if the programmer had typed "= 0". Therefore, such variables are initialized to the null pointer (of the correct type; see also section 5) if they are pointers, and to 0.0 if they are floating-point. Variables with "automatic" duration (i.e. local variables without the static storage class) start out containing garbage, unless they are explicitly initialized. (Nothing useful can be predicted about the garbage.) Dynamically-allocated memory obtained with malloc() and realloc() is also likely to contain garbage, and must be initialized by the calling program, as appropriate. Memory obtained with calloc() is all-bits-0, but this is not necessarily useful for pointer or floating-point values (see question 7.31, and section 5). References: K&R1 Sec. 4.9 pp. 82-4; K&R2 Sec. 4.9 pp. 85-86; ANSI Sec. 3.5.7, Sec. 4.10.3.1, Sec. 4.10.5.3; ISO Sec. 6.5.7, Sec. 7.10.3.1, Sec. 7.10.5.3; H&S Sec. 4.2.8 pp. 72-3, Sec. 4.6 pp. 92-3, Sec. 4.6.2 pp. 94-5, Sec. 4.6.3 p. 96, Sec. 16.1 p. 386.

1.31:

This code, straight out of a book, isn't compiling: f() { char a[] = "Hello, world!"; }

A:

Perhaps you have a pre-ANSI compiler, which doesn't allow initialization of "automatic aggregates" (i.e. non-static local arrays, structures, and unions). As a workaround, you can make the array global or static (if you won't need a fresh copy during any subsequent calls), or replace it with a pointer (if

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

the array won't be written to). (You can always initialize local char * variables to point to string literals, but see question 1.32 below.) If neither of these conditions hold, you'll have to initialize the array by hand with strcpy() when f() is called. See also question 11.29. 1.32: What is the difference between these initializations? char a[] = "string literal"; char *p = "string literal"; My program crashes if I try to assign a new value to p[i]. A: A string literal can be used in two slightly different ways. As an array initializer (as in the declaration of char a[]), it specifies the initial values of the characters in that array. Anywhere else, it turns into an unnamed, static array of characters, which may be stored in read-only memory, which is why you can't safely modify it. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element. (For compiling old code, some compilers have a switch controlling whether strings are writable or not.) See also questions 1.31, 6.1, 6.2, and 6.8. References: K&R2 Sec. 5.5 p. 104; ANSI Sec. 3.1.4, Sec. 3.5.7; ISO Sec. 6.1.4, Sec. 6.5.7; Rationale Sec. 3.1.4; H&S Sec. 2.7.4 pp. 31-2. 1.34: I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one? Use something like extern int func();

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

int (*fp)() = func; When the name of a function appears in an expression like this, it "decays" into a pointer (that is, it has its address implicitly taken), much as an array name does. An explicit declaration for the function is normally needed, since implicit external function declaration does not happen in this case (because the function name in the initialization is not part of a function call). See also question 4.12.

Section 2. Structures, Unions, and Enumerations 2.1: What's the difference between these two declarations? struct x1 { ... }; typedef struct { ... } x2; A: The first form declares a "structure tag"; the second declares a "typedef". The main difference is that the second declaration is of a slightly more abstract type -- its users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it. Why doesn't struct x { ... }; x thestruct; work? A: C is not C++. Typedef names are not automatically generated for structure tags. See also question 2.1 above. Can a structure contain a pointer to itself?

2.2:

2.3:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A: 2.4:

Most certainly.

See question 1.14.

What's the best way of implementing opaque (abstract) data types in C? One good way is for clients to use structure pointers (perhaps additionally hidden behind typedefs) which point to structure types which are not publicly defined. I came across some code that declared a structure like this: struct name { int namelen; char namestr[1]; }; and then did some tricky allocation to make the namestr array act like it had several elements. Is this legal or portable?

A:

2.6:

A:

This technique is popular, although Dennis Ritchie has called it "unwarranted chumminess with the C implementation." An official interpretation has deemed that it is not strictly conforming with the C Standard. (A thorough treatment of the arguments surrounding the legality of the technique is beyond the scope of this list.) It does seem to be portable to all known implementations. (Compilers which check array bounds carefully might issue warnings.) Another possibility is to declare the variable-size element very large, rather than very small; in the case of the above example: ... char namestr[MAXSIZE]; ... where MAXSIZE is larger than any name which will be stored. However, it looks like this technique is disallowed by a strict

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

interpretation of the Standard as well. References: Rationale Sec. 3.5.4.2. 2.7: I heard that structures could be assigned to variables and passed to and from functions, but K&R1 says not. What K&R1 said was that the restrictions on structure operations would be lifted in a forthcoming version of the compiler, and in fact structure assignment and passing were fully functional in Ritchie's compiler even as K&R1 was being published. Although a few early C compilers lacked these operations, all modern compilers support them, and they are part of the ANSI C standard, so there should be no reluctance to use them. (Note that when a structure is assigned, passed, or returned, the copying is done monolithically; anything pointed to by any pointer fields is *not* copied.) References: K&R1 Sec. 6.2 p. 121; K&R2 Sec. 6.2 p. 129; ANSI Sec. 3.1.2.5, Sec. 3.2.2.1, Sec. 3.3.16; ISO Sec. 6.1.2.5, Sec. 6.2.2.1, Sec. 6.3.16; H&S Sec. 5.6.2 p. 133. 2.8: A: Why can't you compare structures? There is no single, good way for a compiler to implement structure comparison which is consistent with C's low-level flavor. A simple byte-by-byte comparison could founder on random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct; see question 2.12). A field-by-field comparison might require unacceptable amounts of repetitive code for large structures. If you need to compare two structures, you'll have to write your own function to do so, field by field. References: K&R2 Sec. 6.2 p. 129; ANSI Sec. 4.11.4.1 footnote 136; Rationale Sec. 3.3.9; H&S Sec. 5.6.2 p. 133.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

2.9: A:

How are structure passing and returning implemented? When structures are passed as arguments to functions, the entire structure is typically pushed on the stack, using as many words as are required. (Programmers often choose to use pointers to structures instead, precisely to avoid this overhead.) Some compilers merely pass a pointer to the structure, though they may have to make a local copy to preserve pass-by-value semantics. Structures are often returned from functions in a location pointed to by an extra, compiler-supplied "hidden" argument to the function. Some older compilers used a special, static location for structure returns, although this made structurevalued functions non-reentrant, which ANSI C disallows. References: ANSI Sec. 2.2.3; ISO Sec. 5.2.3.

2.10:

How can I pass constant values to functions which accept structure arguments? C has no way of generating anonymous structure values. You will have to use a temporary structure variable or a little structurebuilding function. (gcc provides structure constants as an extension, and the mechanism will probably be added to a future revision of the C Standard.) See also question 4.10. How can I read/write structures from/to data files? It is relatively straightforward to write a structure out using fwrite(): fwrite(&somestruct, sizeof somestruct, 1, fp); and a corresponding fread invocation can read it back in. (Under pre-ANSI C, a (char *) cast on the first argument is required. What's important is that fwrite() receive a byte

A:

2.11: A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

pointer, not a structure pointer.) However, data files so written will *not* be portable (see questions 2.12 and 20.5). Note also that if the structure contains any pointers, only the pointer values will be written, and they are most unlikely to be valid when read back in. Finally, note that for widespread portability you must use the "b" flag when fopening the files; see question 12.38. A more portable solution, though it's a bit more work initially, is to write a pair of functions for writing and reading a structure, field-by-field, in a portable (perhaps even humanreadable) way. References: H&S Sec. 15.13 p. 381. 2.12: My compiler is leaving holes in structures, which is wasting space and preventing "binary" I/O to external data files. Can I turn off the padding, or otherwise control the alignment of structure fields? Your compiler may provide an extension to give you this control (perhaps a #pragma; see question 11.20), but there is no standard method. See also question 20.5. References: K&R2 Sec. 6.4 p. 138; H&S Sec. 5.6.4 p. 135. 2.13: Why does sizeof report a larger size than I expect for a structure type, as if there were padding at the end? Structures may have this padding (as well as internal padding), if necessary, to ensure that alignment properties will be preserved when an array of contiguous structures is allocated. Even when the structure is not part of an array, the end padding remains, so that sizeof can always return a consistent size. See question 2.12 above.

A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: H&S Sec. 5.6.7 pp. 139-40. 2.14: How can I determine the byte offset of a field within a structure? ANSI C defines the offsetof() macro, which should be used if available; see . If you don't have it, one possible implementation is #define offsetof(type, mem) ((size_t) \ ((char *)&((type *)0)->mem - (char *)(type *)0)) This implementation is not 100% portable; some compilers may legitimately refuse to accept it. See question 2.15 below for a usage hint. References: ANSI Sec. 4.1.5; ISO Sec. 7.1.6; Rationale Sec. 3.5.4.2; H&S Sec. 11.1 pp. 292-3. 2.15: A: How can I access structure fields by name at run time? Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is offsetb = offsetof(struct a, b) If structp is a pointer to an instance of this structure, and field b is an int (with offset as computed above), b's value can be set indirectly with *(int *)((char *)structp + offsetb) = value; 2.18: This program works correctly, but it dumps core after it finishes. Why? struct list { char *item;

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

struct list *next; } /* Here is the main program. */ main(argc, argv) { ... } A: A missing semicolon causes main() to be declared as returning a structure. (The connection is hard to see because of the intervening comment.) Since structure-valued functions are usually implemented by adding a hidden return pointer (see question 2.9), the generated code for main() tries to accept three arguments, although only two are passed (in this case, by the C start-up code). See also questions 10.9 and 16.4. References: CT&P Sec. 2.3 pp. 21-2. 2.20: A: Can I initialize unions? ANSI Standard C allows an initializer for the first member of a union. There is no standard way of initializing any other member (nor, under a pre-ANSI compiler, is there generally any way of initializing a union at all). References: K&R2 Sec. 6.8 pp. 148-9; ANSI Sec. 3.5.7; ISO Sec. 6.5.7; H&S Sec. 4.6.7 p. 100. 2.22: What is the difference between an enumeration and a set of preprocessor #defines? At the present time, there is little difference. Although many people might have wished otherwise, the C Standard says that enumerations may be freely intermixed with other integral types, without errors. (If such intermixing were disallowed without explicit casts, judicious use of enumerations could catch certain programming errors.)

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Some advantages of enumerations are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enumeration variables are examined, and that they obey block scope. (A compiler may also generate nonfatal warnings when enumerations and integers are indiscriminately mixed, since doing so can still be considered bad style even though it is not strictly illegal.) A disadvantage is that the programmer has little control over those nonfatal warnings; some programmers also resent not having control over the sizes of enumeration variables. References: K&R2 Sec. 2.3 Sec. 3.1.2.5, Sec. 3.5.2, Sec. 6.1.2.5, Sec. 6.5.2, pp. 127-9, Sec. 5.11.2 p. 2.24: A: p. 39, Sec. A4.2 p. 196; ANSI Sec. 3.5.2.2, Appendix E; ISO Sec. 6.5.2.2, Annex F; H&S Sec. 5.5 153.

Is there an easy way to print enumeration values symbolically? No. You can write a little function to map an enumeration constant to a string. (If all you're worried about is debugging, a good debugger should automatically print enumeration constants symbolically.)

Section 3. Expressions 3.1: Why doesn't this code: a[i] = i++; work? A: The subexpression i++ causes a side effect -- it modifies i's value -- which leads to undefined behavior since i is also referenced elsewhere in the same expression. (Note that although the language in K&R suggests that the behavior of this expression is unspecified, the C Standard makes the stronger statement that it is undefined -- see question 11.33.)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: K&R1 Sec. 2.12; K&R2 Sec. 2.12; ANSI Sec. 3.3; ISO Sec. 6.3. 3.2: Under my compiler, the code int i = 7; printf("%d\n", i++ * i++); prints 49. print 56? A: Regardless of the order of evaluation, shouldn't it

Although the postincrement and postdecrement operators ++ and -perform their operations after yielding the former value, the implication of "after" is often misunderstood. It is *not* guaranteed that an increment or decrement is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered "finished" (before the next "sequence point," in ANSI C's terminology; see question 3.8). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards. The behavior of code which contains multiple, ambiguous side effects has always been undefined. (Loosely speaking, by "multiple, ambiguous side effects" we mean any combination of ++, --, =, +=, -=, etc. in a single expression which causes the same object either to be modified twice or modified and then inspected. This is a rough definition; see question 3.8 for a precise one, and question 11.33 for the meaning of "undefined.") Don't even try to find out how your compiler implements such things (contrary to the ill-advised exercises in many C textbooks); as K&R wisely point out, "if you don't know *how* they are done on various machines, that innocence may help to protect you." References: K&R1 Sec. 2.12 p. 50; K&R2 Sec. 2.12 p. 54; ANSI

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Sec. 3.3; ISO Sec. 6.3; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1. 3.3: I've experimented with the code [CENSORED] on several compilers. Some gave i the value 3, some gave 4, but one gave 7. I know the behavior is undefined, but how could it give 7? A: [I apologize for the censorship of the question, but the expression that used to be there was indecent, and by the newly-passed Communications Decency Act of the U.S., I am prohibited from transmitting "indecent" material, whatever that is. Suffice it to say that the expression tried to modify the same variable twice between sequence points. --scs] Undefined behavior means *anything* can happen. See questions 3.9 and 11.33. (Also, note that neither i++ nor ++i is the same as i+1. If you want to increment i, use i=i+1 or i++ or ++i, not some combination. See also question 3.12.) 3.4: Can I use explicit parentheses to force the order of evaluation I want? Even if I don't, doesn't precedence dictate it? Not in general. Operator precedence and explicit parentheses impose only a partial ordering on the evaluation of an expression. In the expression f() + g() * h() although we know that the multiplication will happen before the addition, there is no telling which of the three functions will be called first.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

When you need to ensure the order of subexpression evaluation, you may need to use explicit temporary variables and separate statements. References: K&R1 Sec. 2.12 p. 49, Sec. A.7 p. 185; K&R2 Sec. 2.12 pp. 52-3, Sec. A.7 p. 200. 3.5: But what about the && and || operators? I see code like "while((c = getchar()) != EOF && c != '\n')" ... There is a special exception for those operators (as well as the ?: operator): left-to-right evaluation is guaranteed (as is an intermediate sequence point, see question 3.8). Any book on C should make this clear. References: K&R1 Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R2 Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI Sec. 3.3.13, Sec. 3.3.14, Sec. 3.3.15; ISO Sec. 6.3.13, Sec. 6.3.14, Sec. 6.3.15; H&S Sec. 7.7 pp. 217-8, Sec. 7.8 pp. 218-20, Sec. 7.12.1 p. 229; CT&P Sec. 3.7 pp. 46-7. 3.8: How can I understand these complex expressions? "sequence point"? What's a

A:

A:

A sequence point is the point (at the end of a full expression, or at the ||, &&, ?:, or comma operators, or just before a function call) at which the dust has settled and all side effects are guaranteed to be complete. The ANSI/ISO C Standard states that Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The second sentence can be difficult to understand. It says that if an object is written to within a full expression, any

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

and all accesses to it within the same expression must be for the purposes of computing the value to be written. This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification. See also question 3.9 below. References: ANSI Sec. 2.1.2.3, Sec. 3.3, Appendix B; ISO Sec. 5.1.2.3, Sec. 6.3, Annex C; Rationale Sec. 2.1.2.3; H&S Sec. 7.12.1 pp. 228-9. 3.9: So given a[i] = i++; we don't know which cell of a[] gets written to, but i does get incremented by one. A: *No.* Once an expression or program becomes undefined, *all* aspects of it become undefined. See questions 3.2, 3.3, 11.33, and 11.35. If I'm not using the value of the expression, should I use i++ or ++i to increment a variable? Since the two forms differ only in the value yielded, they are entirely equivalent when only their side effect is needed. See also question 3.3. References: K&R1 Sec. 2.8 p. 43; K&R2 Sec. 2.8 p. 47; ANSI Sec. 3.3.2.4, Sec. 3.3.3.1; ISO Sec. 6.3.2.4, Sec. 6.3.3.1; H&S Sec. 7.4.4 pp. 192-3, Sec. 7.5.8 pp. 199-200.

3.12:

A:

3.14:

Why doesn't the code int a = 1000, b = 1000;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

long int c = a * b; work? A: Under C's integral promotion rules, the multiplication is carried out using int arithmetic, and the result may overflow or be truncated before being promoted and assigned to the long int left-hand side. Use an explicit cast to force long arithmetic: long int c = (long int)a * b; Note that (long int)(a * b) would *not* have the desired effect. A similar problem can arise when two integers are divided, with the result assigned to a floating-point variable. References: K&R1 Sec. 2.7 p. 41; K&R2 Sec. 2.7 p. 44; ANSI Sec. 3.2.1.5; ISO Sec. 6.2.1.5; H&S Sec. 6.3.4 p. 176; CT&P Sec. 3.9 pp. 49-50. 3.16: I have a complicated expression which I have to assign to one of two variables, depending on a condition. Can I use code like this? ((condition) ? a : b) = complicated_expression; A: No. The ?: operator, like most operators, yields a value, and you can't assign to a value. (In other words, ?: does not yield an "lvalue".) If you really want to, you can try something like *((condition) ? &a : &b) = complicated_expression; although this is admittedly not as pretty. References: ANSI Sec. 3.3.15 esp. footnote 50; ISO Sec. 6.3.15; H&S Sec. 7.1 pp. 179-180.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Section 4. Pointers 4.2: I'm trying to declare a pointer and allocate some space for it, but it's not working. What's wrong with this code? char *p; *p = malloc(10); A: The pointer you declared is p, not *p. To make a pointer point somewhere, you just use the name of the pointer: p = malloc(10); It's when you're manipulating the pointed-to memory that you use * as an indirection operator: *p = 'H'; See also questions 1.21, 7.1, and 8.3. References: CT&P Sec. 3.1 p. 28. 4.3: A: Does *p++ increment p, or what it points to? Unary operators like *, ++, and -- all associate (group) from right to left. Therefore, *p++ increments p (and returns the value pointed to by p before the increment). To increment the value pointed to by p, use (*p)++ (or perhaps ++*p, if the order of the side effect doesn't matter). References: K&R1 Sec. 5.1 p. 91; K&R2 Sec. 5.1 p. 95; ANSI Sec. 3.3.2, Sec. 3.3.3; ISO Sec. 6.3.2, Sec. 6.3.3; H&S Sec. 7.4.4 pp. 192-3, Sec. 7.5 p. 193, Secs. 7.5.7,7.5.8 pp. 199200. 4.5: I have a char * pointer that happens to point to some ints, and I want to step it over them. Why doesn't

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

((int *)p)++; work? A: In C, a cast operator does not mean "pretend these bits have a different type, and treat them accordingly"; it is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++. (It is an anomaly in pccderived compilers, and an extension in gcc, that expressions such as the above are ever accepted.) Say what you mean: use p = (char *)((int *)p + 1); or (since p is a char *) simply p += sizeof(int); Whenever possible, you should choose appropriate pointer types in the first place, instead of trying to treat one type as another. References: K&R2 Sec. A7.5 p. 205; ANSI Sec. 3.3.4 (esp. footnote 14); ISO Sec. 6.3.4; Rationale Sec. 3.3.2.4; H&S Sec. 7.1 pp. 179-80. 4.8: I have a function which accepts, and is supposed to initialize, a pointer: void f(ip) int *ip; { static int dummy = 5; ip = &dummy; } But when I call it like this: int *ip;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

f(ip); the pointer in the caller remains unchanged. A: Are you sure the function initialized what you thought it did? Remember that arguments in C are passed by value. The called function altered only the passed copy of the pointer. You'll either want to pass the address of the pointer (the function will end up accepting a pointer-to-a-pointer), or have the function return the pointer. See also questions 4.9 and 4.11.

4.9:

Can I use a void ** pointer to pass a generic pointer to a function by reference? Not portably. There is no generic pointer-to-pointer type in C. void * acts as a generic pointer only because conversions are applied automatically when other pointer types are assigned to and from void *'s; these conversions cannot be performed (the correct underlying pointer type is not known) if an attempt is made to indirect upon a void ** value which points at something other than a void *. I have a function extern int f(int *); which accepts a pointer to an int. reference? A call like f(&5); doesn't seem to work. How can I pass a constant by

A:

4.10:

A:

You can't do this directly. You will have to declare a temporary variable, and then pass its address to the function:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

int five = 5; f(&five); See also questions 2.10, 4.8, and 20.1. 4.11: A: Does C even have "pass by reference"? Not really. Strictly speaking, C always uses pass by value. You can simulate pass by reference yourself, by defining functions which accept pointers and then using the & operator when calling, and the compiler will essentially simulate it for you when you pass an array to a function (by passing a pointer instead, see question 6.4 et al.), but C has nothing truly equivalent to formal pass by reference or C++ reference parameters. (However, function-like preprocessor macros do provide a form of "call by name".) See also questions 4.8 and 20.1. References: K&R1 Sec. 1.8 pp. 24-5, Sec. 5.2 pp. 91-3; K&R2 Sec. 1.8 pp. 27-8, Sec. 5.2 pp. 91-3; ANSI Sec. 3.3.2.2, esp. footnote 39; ISO Sec. 6.3.2.2; H&S Sec. 9.5 pp. 273-4. 4.12: I've seen different methods used for calling functions via pointers. What's the story? Originally, a pointer to a function had to be "turned into" a "real" function, with the * operator (and an extra pair of parentheses, to keep the precedence straight), before calling: int r, func(), (*fp)() = func; r = (*fp)();

A:

It can also be argued that functions are always called via pointers, and that "real" function names always decay implicitly into pointers (in expressions, as they do in initializations;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

see question 1.34). This reasoning, made widespread through pcc and adopted in the ANSI standard, means that

r = fp(); is legal and works correctly, whether fp is the name of a function or a pointer to one. (The usage has always been unambiguous; there is nothing you ever could have done with a function pointer followed by an argument list except call the function pointed to.) An explicit * is still allowed (and recommended, if portability to older compilers is important). See also question 1.34. References: K&R1 Sec. 5.12 p. 116; K&R2 Sec. 5.11 p. 120; ANSI Sec. 3.3.2.2; ISO Sec. 6.3.2.2; Rationale Sec. 3.3.2.2; H&S Sec. 5.8 p. 147, Sec. 7.4.3 p. 190.

Section 5. Null Pointers 5.1: A: What is this infamous null pointer, anyway? The language definition states that for each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is "guaranteed to compare unequal to a pointer to any object or function." That is, the address-of operator & will never yield a null pointer, nor will a successful call to malloc(). (malloc() does return a null pointer when it fails, and this is a typical use of null pointers: as a "special" pointer value with some other meaning, usually "not allocated" or "not pointing anywhere yet.") A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object or function; an uninitialized pointer might point anywhere. See

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

also questions 1.30, 7.1, and 7.31. As mentioned above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different. Although programmers need not know the internal values, the compiler must always be informed which type of null pointer is required, so that it can make the distinction if necessary (see questions 5.2, 5.5, and 5.6 below). References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ANSI Sec. 3.2.2.3; ISO Sec. 6.2.2.3; Rationale Sec. 3.2.2.3; H&S Sec. 5.3.2 pp. 121-3. 5.2: A: How do I get a null pointer in my programs? According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal: char *p = 0; if(p != 0) (See also question 5.3.) However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. To generate a null pointer in a function call context, an explicit cast may be required, to force the 0 to be recognized as a pointer. For example, the Unix system call execl takes a variable-length, null-pointer-terminated list of character pointer arguments, and is correctly called like this: execl("/bin/sh", "sh", "-c", "date", (char *)0);

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

If the (char *) cast on the last argument were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong .) When function prototypes are in scope, argument passing becomes an "assignment context," and most casts may safely be omitted, since the prototype tells the compiler that a pointer is required, and of which type, enabling it to correctly convert an unadorned 0. Function prototypes cannot provide the types for variable arguments in variable-length argument lists however, so explicit casts are still required for those arguments. (See also question 15.3.) It is safest to properly cast all null pointer constants in function calls: to guard against varargs functions or those without prototypes, to allow interim use of non-ANSI compilers, and to demonstrate that you know what you are doing. (Incidentally, it's also a simpler rule to remember.) Summary: Unadorned 0 okay: initialization assignment comparison function call, prototype in scope, fixed argument References: K&R1 Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R2 Sec. A7.10 p. 207, Sec. A7.17 p. 209; ANSI Sec. 3.2.2.3; ISO Sec. 6.2.2.3; H&S Sec. 4.6.3 p. 95, Sec. 6.2.7 p. 171. variable argument in varargs function call Explicit cast required: function call, no prototype in scope

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

5.3:

Is the abbreviated pointer comparison "if(p)" to test for nonnull pointers valid? What if the internal representation for null pointers is nonzero? When C requires the Boolean value of an expression (in the if, while, for, and do statements, and with the &&, ||, !, and ?: operators), a false value is inferred when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes if(expr) where "expr" is any expression at all, the compiler essentially acts as if it had been written as if((expr) != 0) Substituting the trivial pointer expression "p" for "expr," we have if(p) is equivalent to if(p != 0)

A:

and this is a comparison context, so the compiler can tell that the (implicit) 0 is actually a null pointer constant, and use the correct null pointer value. There is no trickery involved here; compilers do work this way, and generate identical code for both constructs. The internal representation of a null pointer does *not* matter. The boolean negation operator, !, can be described as follows: !expr is essentially equivalent to or to (expr)?0:1 ((expr) == 0)

which leads to the conclusion that if(!p) is equivalent to if(p == 0)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

"Abbreviations" such as if(p), though perfectly legal, are considered by some to be bad style (and by others to be good style; see question 17.10). See also question 9.2. References: K&R2 Sec. A7.4.7 p. 204; ANSI Sec. 3.3.3.3, Sec. 3.3.9, Sec. 3.3.13, Sec. 3.3.14, Sec. 3.3.15, Sec. 3.6.4.1, Sec. 3.6.5; ISO Sec. 6.3.3.3, Sec. 6.3.9, Sec. 6.3.13, Sec. 6.3.14, Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5; H&S Sec. 5.3.2 p. 122. 5.4: A: What is NULL and how is it #defined? As a matter of style, many programmers prefer not to have unadorned 0's scattered through their programs. Therefore, the preprocessor macro NULL is #defined (by or ) with the value 0, possibly cast to (void *) (see also question 5.6). A programmer who wishes to make explicit the distinction between 0 the integer and 0 the null pointer constant can then use NULL whenever a null pointer is required. Using NULL is a stylistic convention only; the preprocessor turns NULL back into 0 which is then recognized by the compiler, in pointer contexts, as before. In particular, a cast may still be necessary before NULL (as before 0) in a function call argument. The table under question 5.2 above applies for NULL as well as 0 (an unadorned NULL is equivalent to an unadorned 0). NULL should *only* be used for pointers; see question 5.9. References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ANSI Sec. 4.1.5, Sec. 3.2.2.3; ISO Sec. 7.1.6, Sec. 6.2.2.3; Rationale Sec. 4.1.5; H&S Sec. 5.3.2 p. 122, Sec. 11.1 p. 292.

5.5:

How should NULL be defined on a machine which uses a nonzero bit

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

pattern as the internal representation of a null pointer? A: The same as on any other machine: as 0 (or ((void *)0)). Whenever a programmer requests a null pointer, either by writing "0" or "NULL," it is the compiler's responsibility to generate whatever bit pattern the machine uses for that null pointer. Therefore, #defining NULL as 0 on a machine for which internal null pointers are nonzero is as valid as on any other: the compiler must always be able to generate the machine's correct null pointers in response to unadorned 0's seen in pointer contexts. See also questions 5.2, 5.10, and 5.17. References: ANSI Sec. 4.1.5; ISO Sec. 7.1.6; Rationale Sec. 4.1.5. 5.6: If NULL were defined as follows: #define NULL ((char *)0) wouldn't that make function calls which pass an uncast NULL work? A: Not in general. The problem is that there are machines which use different internal representations for pointers to different types of data. The suggested definition would make uncast NULL arguments to functions expecting pointers to characters work correctly, but pointer arguments of other types would still be problematical, and legal constructions such as FILE *fp = NULL; could fail. Nevertheless, ANSI C allows the alternate definition #define NULL ((void *)0)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

for NULL. Besides potentially helping incorrect programs to work (but only on machines with homogeneous pointers, thus questionably valid assistance), this definition may catch programs which use NULL incorrectly (e.g. when the ASCII NUL character was really intended; see question 5.9). References: Rationale Sec. 4.1.5. 5.9: If NULL and 0 are equivalent as null pointer constants, which should I use? Many programmers believe that NULL should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding NULL and 0 is only compounded by hiding 0 behind a macro, and prefer to use unadorned 0 instead. There is no one right answer. (See also questions 9.2 and 17.10.) C programmers must understand that NULL and 0 are interchangeable in pointer contexts, and that an uncast 0 is perfectly acceptable. Any usage of NULL (as opposed to 0) should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's. NULL should *not* be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (Furthermore, ANSI allows the definition of NULL to be ((void *)0), which will not work at all in nonpointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition #define NUL '\0' if you must. References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

5.10:

But wouldn't it be better to use NULL (rather than 0), in case the value of NULL changes, perhaps on a machine with nonzero internal null pointers? No. (Using NULL may be preferable, but not for this reason.) Although symbolic constants are often used in place of numbers because the numbers might change, this is *not* the reason that NULL is used in place of 0. Once again, the language guarantees that source-code 0's (in pointer contexts) generate null pointers. NULL is used only as a stylistic convention. See questions 5.5 and 9.2. I use the preprocessor macro #define Nullptr(type) (type *)0 to help me build null pointers of the correct type.

A:

5.12:

A:

This trick, though popular and superficially attractive, does not buy much. It is not needed in assignments and comparisons; see question 5.2. It does not even save keystrokes. Its use may suggest to the reader that the program's author is shaky on the subject of null pointers, requiring that the #definition of the macro, its invocations, and *all* other pointer usages be checked. See also questions 9.1 and 10.2. This is strange. pointer is not? NULL is guaranteed to be 0, but the null

5.13:

A:

When the term "null" or "NULL" is casually used, one of several things may be meant: 1. The conceptual null pointer, the abstract language concept defined in question 5.1. It is implemented with... The internal (or run-time) representation of a null pointer, which may or may not be all-bits-0 and which may be different for different pointer types. The actual

2.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

values should be of concern only to compiler writers. Authors of C programs never see them, since they use... 3. The null pointer constant, which is a constant integer 0 (see question 5.2). It is often hidden behind... The NULL macro, which is #defined to be "0" or "((void *)0)" (see question 5.4). Finally, as red herrings, we have... The ASCII null character (NUL), which does have all bits zero, but has no necessary relation to the null pointer except in name; and... The "null string," which is another name for the empty string (""). Using the term "null string" can be confusing in C, because an empty string involves a null ('\0') character, but *not* a null pointer, which brings us full circle...

4.

5.

6.

This article uses the phrase "null pointer" (in lower case) for sense 1, the character "0" or the phrase "null pointer constant" for sense 3, and the capitalized word "NULL" for sense 4. 5.14: Why is there so much confusion surrounding null pointers? do these questions come up so often? Why

A:

C programmers traditionally like to know more than they need to about the underlying machine implementation. The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) may seem to suggest that the value could change some day, or on some weird machine. The construct "if(p == 0)" is easily misread as calling for conversion of p to an integral type, rather than 0 to a pointer type, before the comparison. Finally, the distinction between the several uses of the term "null" (listed in question 5.13 above) is often overlooked.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

One good way to wade out of the confusion is to imagine that C used a keyword (perhaps "nil", like Pascal) as a null pointer constant. The compiler could either turn "nil" into the correct type of null pointer when it could determine the type from the source code, or complain when it could not. Now in fact, in C the keyword for a null pointer constant is not "nil" but "0", which works almost as well, except that an uncast "0" in a nonpointer context generates an integer zero instead of an error message, and if that uncast 0 was supposed to be a null pointer constant, the code may not work. 5.15: I'm confused. stuff. I just can't understand all this null pointer

A:

Follow these two simple rules: 1. When you want a null pointer constant in source code, use "0" or "NULL". If the usage of "0" or "NULL" is an argument in a function call, cast it to the pointer type expected by the function being called.

2.

The rest of the discussion has to do with other people's misunderstandings, with the internal representation of null pointers (which you shouldn't need to know), and with ANSI C refinements. Understand questions 5.1, 5.2, and 5.4, and consider 5.3, 5.9, 5.13, and 5.14, and you'll do fine. 5.16: Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? If for no other reason, doing so would be ill-advised because it would unnecessarily constrain implementations which would otherwise naturally represent null pointers by special, nonzero bit patterns, particularly when those values would trigger

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

automatic hardware traps for invalid accesses. Besides, what would such a requirement really accomplish? Proper understanding of null pointers does not require knowledge of the internal representation, whether zero or nonzero. Assuming that null pointers are internally zero does not make any code easier to write (except for a certain ill-advised usage of calloc(); see question 7.31). Known-zero internal pointers would not obviate casts in function calls, because the *size* of the pointer might still be different from that of an int. (If "nil" were used to request null pointers, as mentioned in question 5.14 above, the urge to assume an internal zero representation would not even arise.) 5.17: Seriously, have any actual machines really used nonzero null pointers, or different representations for pointers to different types? The Prime 50 series used segment 07777, offset 0 for the null pointer, at least for PL/I. Later models used segment 0, offset 0 for null pointers in C, necessitating new instructions such as TCNP (Test C Null Pointer), evidently as a sop to all the extant poorly-written C code which made incorrect assumptions. Older, word-addressed Prime machines were also notorious for requiring larger byte pointers (char *'s) than word pointers (int *'s). The Eclipse MV series from Data General has three architecturally supported pointer formats (word, byte, and bit pointers), two of which are used by C compilers: byte pointers for char * and void *, and word pointers for everything else. Some Honeywell-Bull mainframes use the bit pattern 06000 for (internal) null pointers. The CDC Cyber 180 Series has 48-bit pointers consisting of a ring, segment, and offset. Most users (in ring 11) have null pointers of 0xB00000000000. It was common on old CDC onescomplement machines to use an all-one-bits word as a special

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

flag for all kinds of data, including invalid addresses. The old HP 3000 series uses a different addressing scheme for byte addresses than for word addresses; like several of the machines above it therefore uses different representations for char * and void * pointers than for other pointers. The Symbolics Lisp Machine, a tagged architecture, does not even have conventional numeric pointers; it uses the pair (basically a nonexistent handle) as a C null pointer. Depending on the "memory model" in use, 8086-family processors (PC compatibles) may use 16-bit data pointers and 32-bit function pointers, or vice versa. Some 64-bit Cray machines represent int * in the lower 48 bits of a word; char * additionally uses the upper 16 bits to indicate a byte address within a word. References: K&R1 Sec. A14.4 p. 211. 5.20: What does a run-time "null pointer assignment" error mean? do I track it down? How

A:

This message, which typically occurs with MS-DOS compilers (see, therefore, section 19) means that you've written, via a null (perhaps because uninitialized) pointer, to location 0. (See also question 16.8.) A debugger may let you set a data breakpoint or watchpoint or something on location 0. Alternatively, you could write a bit of code to stash away a copy of 20 or so bytes from location 0, and periodically check that the memory at location 0 hasn't changed.

Section 6.

Arrays and Pointers

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

6.1:

I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn't it work? The declaration extern char *a simply does not match the actual definition. The type pointer-to-type-T is not the same as arrayof-type-T. Use extern char a[]. References: ANSI Sec. 3.5.4.2; ISO Sec. 6.5.4.2; CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5.

A:

6.2: A:

But I heard that char a[] was identical to char *a. Not at all. (What you heard has to do with formal parameters to functions; see question 6.4.) Arrays are not pointers. The array declaration char a[6] requests that space for six characters be set aside, to be known by the name "a." That is, there is a location named "a" at which six characters can sit. The pointer declaration char *p, on the other hand, requests a place which holds a pointer, to be known by the name "p." This pointer can point almost anywhere: to any char, or to any contiguous array of chars, or nowhere (see also questions 5.1 and 1.30). As usual, a picture is worth a thousand words. char a[] = "hello"; char *p = "world"; would initialize data structures which could be represented like this: +---+---+---+---+---+---+ a: | h | e | l | l | o |\0 | +---+---+---+---+---+---+ +-----+ +---+---+---+---+---+---+ p: | *======> | w | o | r | l | d |\0 | +-----+ +---+---+---+---+---+---+ The declarations

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

It is important to realize that a reference like *x*[3] generates different code depending on whether *x* is an array or a pointer. Given the declarations above, when the compiler sees the expression a[3], it emits code to start at the location "a," move three past it, and fetch the character there. When it sees the expression p[3], it emits code to start at the location "p," fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to. In other words, a[3] is three places past (the start of) the object *named* a, while p[3] is three places past the object *pointed to* by p. In the example above, both a[3] and p[3] happen to be the character 'l', but the compiler gets there differently. References: K&R2 Sec. 5.5 p. 104; CT&P Sec. 4.5 pp. 64-5. 6.3: So what is meant by the "equivalence of pointers and arrays" in C? Much of the confusion surrounding arrays and pointers in C can be traced to a misunderstanding of this statement. Saying that arrays and pointers are "equivalent" means neither that they are identical nor even interchangeable. "Equivalence" refers to the following key definition: An lvalue of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T. (The exceptions are when the array is the operand of a sizeof or & operator, or is a string literal initializer for a character array.) As a consequence of this definition, the compiler doesn't apply the array subscripting operator [] that differently to arrays and pointers, after all. In an expression of the form a[i], the array decays into a pointer, following the rule above, and is

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

then subscripted just as would be a pointer variable in the expression p[i] (although the eventual memory accesses will be different, as explained in question 6.2). If you were to assign the array's address to the pointer: p = a; then p[3] and a[3] would access the same element. See also question 6.8. References: K&R1 Sec. 5.3 pp. 93-6; K&R2 Sec. 5.3 p. 99; ANSI Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6; ISO Sec. 6.2.2.1, Sec. 6.3.2.1, Sec. 6.3.6; H&S Sec. 5.4.1 p. 124. 6.4: Then why are array and pointer declarations interchangeable as function formal parameters? It's supposed to be a convenience. Since arrays decay immediately into pointers, an array is never actually passed to a function. Allowing pointer parameters to be declared as arrays is a simply a way of making it look as though the array was being passed -- a programmer may wish to emphasize that a parameter is traditionally treated as if it were an array, or that an array (strictly speaking, the address) is traditionally passed. As a convenience, therefore, any parameter declarations which "look like" arrays, e.g. f(a) char a[]; { ... } are treated by the compiler as if they were pointers, since that is what the function will receive if an array is passed: f(a) char *a;

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

{ ... } This conversion holds only within function formal parameter declarations, nowhere else. If the conversion bothers you, avoid it; many people have concluded that the confusion it causes outweighs the small advantage of having the declaration "look like" the call or the uses within the function. See also question 6.21. References: K&R1 Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R2 Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; ANSI Sec. 3.5.4.3, Sec. 3.7.1, Sec. 3.9.6; ISO Sec. 6.5.4.3, Sec. 6.7.1, Sec. 6.9.6; H&S Sec. 9.3 p. 271; CT&P Sec. 3.3 pp. 33-4. 6.7: A: How can an array be an lvalue, if you can't assign to it? The ANSI C Standard defines a "modifiable lvalue," which an array is not. References: ANSI Sec. 3.2.2.1; ISO Sec. 6.2.2.1; Rationale Sec. 3.2.2.1; H&S Sec. 7.1 p. 179. 6.8: Practically speaking, what is the difference between arrays and pointers? Arrays automatically allocate space, but can't be relocated or resized. Pointers must be explicitly assigned to point to allocated space (perhaps using malloc), but can be reassigned (i.e. pointed at different objects) at will, and have many other uses besides serving as the base of blocks of memory. Due to the so-called equivalence of arrays and pointers (see question 6.3), arrays and pointers often seem interchangeable, and in particular a pointer to a block of memory assigned by malloc is frequently treated (and can be referenced using []) exactly as if it were a true array. See questions 6.14 and

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

6.16.

(Be careful with sizeof, though.)

See also questions 1.32 and 20.14. 6.9: Someone explained to me that arrays were really just constant pointers. This is a bit of an oversimplification. An array name is "constant" in that it cannot be assigned to, but an array is *not* a pointer, as the discussion and pictures in question 6.2 should make clear. See also questions 6.3 and 6.8. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? Yes, Virginia, array subscripting is commutative in C. This curious fact follows from the pointer definition of array subscripting, namely that a[e] is identical to *((a)+(e)), for *any* two expressions a and e, as long as one of them is a pointer expression and one is integral. This unsuspected commutativity is often mentioned in C texts as if it were something to be proud of, but it finds no useful application outside of the Obfuscated C Contest (see question 20.36). References: Rationale Sec. 3.3.2.1; H&S Sec. 5.4.1 p. 124, Sec. 7.4.1 pp. 186-7. 6.12: Since array references decay into pointers, if arr is an array, what's the difference between arr and &arr? The type. In Standard C, &arr yields a pointer, of type pointer-to-arrayof-T, to the entire array. (In pre-ANSI C, the & in &arr generally elicited a warning, and was generally ignored.) Under all C compilers, a simple reference (without an explicit &) to an array yields a pointer, of type pointer-to-T, to the array's first element. (See also questions 6.3, 6.13, and 6.18.)

A:

6.11:

A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: ANSI Sec. 3.2.2.1, Sec. 3.3.3.2; ISO Sec. 6.2.2.1, Sec. 6.3.3.2; Rationale Sec. 3.3.3.2; H&S Sec. 7.5.6 p. 198. 6.13: A: How do I declare a pointer to an array? Usually, you don't want to. When people speak casually of a pointer to an array, they usually mean a pointer to its first element. Instead of a pointer to an array, consider using a pointer to one of the array's elements. Arrays of type T decay into pointers to type T (see question 6.3), which is convenient; subscripting or incrementing the resultant pointer will access the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally useful only when operating on arrays of arrays, if at all. (See question 6.18.) If you really need to declare a pointer to an entire array, use something like "int (*ap)[N];" where N is the size of the array. (See also question 1.21.) If the size of the array is unknown, N can in principle be omitted, but the resulting type, "pointer to array of unknown size," is useless. See also question 6.12 above. References: ANSI Sec. 3.2.2.1; ISO Sec. 6.2.2.1. 6.14: How can I set an array's size at compile time? How can I avoid fixed-sized arrays? The equivalence between arrays and pointers (see question 6.3) allows a pointer to malloc'ed memory to simulate an array quite effectively. After executing #include int *dynarray = (int *)malloc(10 * sizeof(int));

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(and if the call to malloc() succeeds), you can reference dynarray[i] (for i from 0 to 9) just as if dynarray were a conventional, statically-allocated array (int a[10]). See also question 6.16. 6.15: How can I declare local arrays of a size matching a passed-in array? You can't, in C. Array dimensions must be compile-time constants. (gcc provides parameterized arrays as an extension.) You'll have to use malloc(), and remember to call free() before the function returns. See also questions 6.14, 6.16, 6.19, 7.22, and maybe 7.32. References: ANSI Sec. 3.4, Sec. 3.5.4.2; ISO Sec. 6.4, Sec. 6.5.4.2. 6.16: A: How can I dynamically allocate a multidimensional array? It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." Here is a two-dimensional example: #include int **array1 = (int **)malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array1[i] = (int *)malloc(ncolumns * sizeof(int)); (In real code, of course, all of malloc's return values would be checked.) You can keep the array's contents contiguous, while making later reallocation of individual rows difficult, with a bit of explicit pointer arithmetic: int **array2 = (int **)malloc(nrows * sizeof(int *));

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int)); for(i = 1; i < nrows; i++) array2[i] = array2[0] + i * ncolumns; In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: arrayx[i][j] (for 0 <= i <= NROWS and 0 <= j <= NCOLUMNS). If the double indirection implied by the above schemes is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array: int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int)); However, you must now perform subscript calculations manually, accessing the i,jth element with array3[i * ncolumns + j]. (A macro could hide the explicit calculation, but invoking it would require parentheses and commas which wouldn't look exactly like multidimensional array syntax, and the macro would need access to at least one of the dimensions, as well. See also question 6.19.) Finally, you could use pointers to arrays: int (*array4)[NCOLUMNS] = (int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4)); but the syntax starts getting horrific and at most one dimension may be specified at run time. With all of these techniques, you may of course need to remember to free the arrays (which may take several steps; see question 7.23) when they are no longer needed, and you cannot necessarily intermix dynamically-allocated arrays with conventional, statically-allocated ones (see question 6.20, and also question 6.18).

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

All of these techniques can also be extended to three or more dimensions. 6.17: Here's a neat trick: if I write int realarray[10]; int *array = &realarray[-1]; I can treat "array" as if it were a 1-based array. A: Although this technique is attractive (and was used in old editions of the book _Numerical Recipes in C_), it does not conform to the C standards. Pointer arithmetic is defined only as long as the pointer points within the same allocated block of memory, or to the imaginary "terminating" element one past it; otherwise, the behavior is undefined, *even if the pointer is not dereferenced*. The code above could fail if, while subtracting the offset, an illegal address were generated (perhaps because the address tried to "wrap around" past the beginning of some memory segment). References: K&R2 Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6; ANSI Sec. 3.3.6; ISO Sec. 6.3.6; Rationale Sec. 3.2.2.3. 6.18: My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer. The rule (see question 6.3) by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a twodimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays can be confusing, and must be treated carefully; see also question 6.13. (The confusion is heightened by the existence of incorrect compilers, including some old versions of pcc and pcc-derived lints, which improperly accept assignments of multi-dimensional arrays to multi-level pointers.)

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

If you are passing a two-dimensional array to a function: int array[NROWS][NCOLUMNS]; f(array); the function's declaration must match: f(int a[][NCOLUMNS]) { ... } or f(int (*ap)[NCOLUMNS]) { ... } /* ap is a pointer to an array */

In the first declaration, the compiler performs the usual implicit parameter rewriting of "array of array" to "pointer to array" (see questions 6.3 and 6.4); in the second form the pointer declaration is explicit. Since the called function does not allocate space for the array, it does not need to know the overall size, so the number of rows, NROWS, can be omitted. The "shape" of the array is still important, so the column dimension NCOLUMNS (and, for three- or more dimensional arrays, the intervening ones) must be retained. If a function is already declared as accepting a pointer to a pointer, it is probably meaningless to pass a two-dimensional array directly to it. See also questions 6.12 and 6.15. References: K&R1 Sec. 5.10 p. 110; K&R2 Sec. 5.9 p. 113; H&S Sec. 5.4.3 p. 126. 6.19: How do I write functions which accept two-dimensional arrays when the "width" is not known at compile time? It's not easy. One way is to pass in a pointer to the [0][0]

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

element, along with the two dimensions, and simulate array subscripting "by hand:" f2(aryp, nrows, ncolumns) int *aryp; int nrows, ncolumns; { ... array[i][j] is accessed as aryp[i * ncolumns + j] ... } This function could be called with the array from question 6.18 as f2(&array[0][0], NROWS, NCOLUMNS); It must be noted, however, that a program which performs multidimensional array subscripting "by hand" in this way is not in strict conformance with the ANSI C Standard; according to an official interpretation, the behavior of accessing (&array[0][0])[x] is not defined for x >= NCOLUMNS. gcc allows local arrays to be declared having sizes which are specified by a function's arguments, but this is a nonstandard extension. When you want to be able to use a function on multidimensional arrays of various sizes, one solution is to simulate all the arrays dynamically, as in question 6.16. See also questions 6.18, 6.20, and 6.15. References: ANSI Sec. 3.3.6; ISO Sec. 6.3.6. 6.20: How can I use statically- and dynamically-allocated multidimensional arrays interchangeably when passing them to functions? There is no single perfect method. int array[NROWS][NCOLUMNS]; Given the declarations

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

int int int int

**array1; **array2; *array3; (*array4)[NCOLUMNS];

/* ragged */ /* contiguous */ /* "flattened" */

with the pointers initialized as in the code fragments in question 6.16, and functions declared as f1(int a[][NCOLUMNS], int nrows, int ncolumns); f2(int *aryp, int nrows, int ncolumns); f3(int **pp, int nrows, int ncolumns); where f1() accepts a conventional two-dimensional array, f2() accepts a "flattened" two-dimensional array, and f3() accepts a pointer-to-pointer, simulated array (see also questions 6.18 and 6.19), the following calls should work as expected: f1(array, NROWS, NCOLUMNS); f1(array4, nrows, NCOLUMNS); f2(&array[0][0], NROWS, NCOLUMNS); f2(*array, NROWS, NCOLUMNS); f2(*array2, nrows, ncolumns); f2(array3, nrows, ncolumns); f2(*array4, nrows, NCOLUMNS); f3(array1, nrows, ncolumns); f3(array2, nrows, ncolumns); The following two calls would probably work on most systems, but involve questionable casts, and work only if the dynamic ncolumns matches the static NCOLUMNS: f1((int (*)[NCOLUMNS])(*array2), nrows, ncolumns); f1((int (*)[NCOLUMNS])array3, nrows, ncolumns); It must again be noted that passing &array[0][0] (or, equivalently, *array) to f2() is not strictly conforming; see question 6.19.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

If you can understand why all of the above calls work and are written as they are, and if you understand why the combinations that are not listed would not work, then you have a *very* good understanding of arrays and pointers in C. Rather than worrying about all of this, one approach to using multidimensional arrays of various sizes is to make them *all* dynamic, as in question 6.16. If there are no static multidimensional arrays -- if all arrays are allocated like array1 or array2 in question 6.16 -- then all functions can be written like f3(). 6.21: Why doesn't sizeof properly report the size of an array when the array is a parameter to a function? The compiler pretends that the array parameter was declared as a pointer (see question 6.4), and sizeof reports the size of the pointer. References: H&S Sec. 7.5.2 p. 195.

A:

Section 7. Memory Allocation 7.1: Why doesn't this fragment work? char *answer; printf("Type something:\n"); gets(answer); printf("You typed \"%s\"\n", answer); A: The pointer variable answer(), which is handed to gets() as the location into which the response should be stored, has not been set to point to any valid storage. That is, we cannot say where the pointer answer() points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that answer() starts out as a null pointer. See questions 1.30 and 5.1.)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation: #include #include char answer[100], *p; printf("Type something:\n"); fgets(answer, sizeof answer, stdin); if((p = strchr(answer, '\n')) != NULL) *p = '\0'; printf("You typed \"%s\"\n", answer); This example also uses fgets() instead of gets(), so that the end of the array cannot be overwritten. (See question 12.23. Unfortunately for this example, fgets() does not automatically delete the trailing \n, as gets() would.) It would also be possible to use malloc() to allocate the answer buffer. 7.2: I can't get strcat() to work. I tried

char *s1 = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); but I got strange results. A: As in question 7.1 above, the main problem here is that space for the concatenated result is not properly allocated. C does not provide an automatically-managed string type. C compilers only allocate memory for objects explicitly mentioned in the source code (in the case of "strings," this includes character arrays and string literals). The programmer must arrange for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or by calling malloc().

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

strcat() performs no allocation; the second string is appended to the first one, in place. Therefore, one fix would be to declare the first string as an array: char s1[20] = "Hello, "; Since strcat() returns the value of its first argument (s1, in this case), the variable s3 is superfluous. The original call to strcat() in the question actually has two problems: the string literal pointed to by s1, besides not being big enough for any concatenated text, is not necessarily writable at all. See question 1.32. References: CT&P Sec. 3.2 p. 32. 7.3: But the man page for strcat() says that it takes two char *'s as arguments. How am I supposed to know to allocate things? In general, when using pointers you *always* have to consider memory allocation, if only to make sure that the compiler is doing it for you. If a library function's documentation does not explicitly mention allocation, it is usually the caller's problem. The Synopsis section at the top of a Unix-style man page or in the ANSI C standard can be misleading. The code fragments presented there are closer to the function definitions used by an implementor than the invocations used by the caller. In particular, many functions which accept pointers (e.g. to structures or strings) are usually called with the address of some object (a structure, or an array -- see questions 6.3 and 6.4). Other common examples are time() (see question 13.12) and stat(). 7.5: I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Make sure that the pointed-to memory is properly allocated. The returned pointer should be to a statically-allocated buffer, or to a buffer passed in by the caller, or to memory obtained with malloc(), but *not* to a local (automatic) array. In other words, never do something like char *itoa(int n) { char retbuf[20]; sprintf(retbuf, "%d", n); return retbuf; }

/* WRONG */ /* WRONG */

One fix (which is imperfect, especially if the function in question is called recursively, or if several of its return values are needed simultaneously) would be to declare the return buffer as static char retbuf[20]; See also questions 12.21 and 20.1. References: ANSI Sec. 3.1.2.4; ISO Sec. 6.1.2.4. 7.6: Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to malloc()? Have you #included , or otherwise arranged for malloc() to be declared properly? References: H&S Sec. 4.7 p. 101. 7.7: Why does some code carefully cast the values returned by malloc to the pointer type being allocated? Before ANSI/ISO Standard C introduced the void * generic pointer type, these casts were typically required to silence warnings

A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(and perhaps induce conversions) when assigning between incompatible pointer types. (Under ANSI/ISO Standard C, these casts are no longer necessary.) References: H&S Sec. 16.1 pp. 386-7. 7.8: I see code like char *p = malloc(strlen(s) + 1); strcpy(p, s); Shouldn't that be malloc((strlen(s) + 1) * sizeof(char))? A: It's never necessary to multiply by sizeof(char), since sizeof(char) is, by definition, exactly 1. (On the other hand, multiplying by sizeof(char) doesn't hurt, and may help by introducing a size_t into the expression.) See also question 8.9. References: ANSI Sec. 3.3.3.4; ISO Sec. 6.3.3.4; H&S Sec. 7.5.2 p. 195. 7.14: I've heard that some operating systems don't actually allocate malloc'ed memory until the program tries to use it. Is this legal? It's hard to say. The Standard doesn't say that systems can act this way, but it doesn't explicitly say that they can't, either. References: ANSI Sec. 4.10.3; ISO Sec. 7.10.3. 7.16: I'm allocating a large array for some numeric work, using the line double *array = malloc(256 * 256 * sizeof(double)); malloc() isn't returning null, but the program is acting strangely, as if it's overwriting memory, or malloc() isn't

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

allocating as much as I asked for, or something. A: Notice that 256 x 256 is 65,536, which will not fit in a 16-bit int, even before you multiply it by sizeof(double). If you need to allocate this much memory, you'll have to be careful. If size_t (the type accepted by malloc()) is a 32-bit type on your machine, but int is 16 bits, you might be able to get away with writing 256 * (256 * sizeof(double)) (see question 3.14). Otherwise, you'll have to break your data structure up into smaller chunks, or use a 32-bit machine, or use some nonstandard memory allocation routines. See also question 19.23. I've got 8 meg of memory in my PC. malloc() 640K or so? Why can I only seem to

7.17:

A:

Under the segmented architecture of PC compatibles, it can be difficult to use more than 640K with any degree of transparency. See also question 19.23. My program is crashing, apparently somewhere down inside malloc, but I can't see anything wrong with it. It is unfortunately very easy to corrupt malloc's internal data structures, and the resulting problems can be stubborn. The most common source of problems is writing more to a malloc'ed region than it was allocated to hold; a particularly common bug is to malloc(strlen(s)) instead of strlen(s) + 1. Other problems may involve using pointers to freed storage, freeing pointers twice, freeing pointers not obtained from malloc, or trying to realloc a null pointer (see question 7.30). See also questions 7.26, 16.8, and 18.2.

7.19:

A:

7.20:

You can't use dynamically-allocated memory after you free it, can you? No. Some early documentation for malloc() stated that the contents of freed memory were "left undisturbed," but this ill-

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

advised guarantee was never universal and is not required by the C Standard. Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list: struct list *listp, *nextp; for(listp = base; listp != NULL; listp = nextp) { nextp = listp->next; free((void *)listp); } and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer. References: K&R2 Sec. 7.8.5 p. 167; ANSI Sec. 4.10.3; ISO Sec. 7.10.3; Rationale Sec. 4.10.3.2; H&S Sec. 16.2 p. 387; CT&P Sec. 7.10 p. 95. 7.21: Why isn't a pointer null after calling free()? How unsafe is it to use (assign, compare) a pointer value after it's been freed? When you call free(), the memory pointed to by the passed pointer is freed, but the value of the pointer in the caller remains unchanged, because C's pass-by-value semantics mean that called functions never permanently change the values of their arguments. (See also question 4.8.) A pointer value which has been freed is, strictly speaking, invalid, and *any* use of it, even if is not dereferenced can theoretically lead to trouble, though as a quality of implementation issue, most implementations will probably not go out of their way to generate exceptions for innocuous uses of invalid pointers.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: ANSI Sec. 4.10.3; ISO Sec. 7.10.3; Rationale Sec. 3.2.2.3. 7.22: When I call malloc() to allocate memory for a local pointer, do I have to explicitly free() it? Yes. Remember that a pointer is different from what it points to. Local variables are deallocated when the function returns, but in the case of a pointer variable, this means that the pointer is deallocated, *not* what it points to. Memory allocated with malloc() always persists until you explicitly free it. In general, for every call to malloc(), there should be a corresponding call to free(). I'm allocating structures which contain pointers to other dynamically-allocated objects. When I free a structure, do I have to free each subsidiary pointer first? Yes. In general, you must arrange that each pointer returned from malloc() be individually passed to free(), exactly once (if it is freed at all). A good rule of thumb is that for each call to malloc() in a program, you should be able to point at the call to free() which frees the memory allocated by that malloc() call. See also question 7.24. 7.24: A: Must I free allocated memory before the program exits? You shouldn't have to. A real operating system definitively reclaims all memory when a program exits. Nevertheless, some personal computers are said not to reliably recover memory, and all that can be inferred from the ANSI/ISO C Standard is that this is a "quality of implementation issue." References: ANSI Sec. 4.10.3.2; ISO Sec. 7.10.3.2.

A:

7.23:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

7.25:

I have a program which mallocs and later frees a lot of memory, but memory usage (as reported by ps) doesn't seem to go back down. Most implementations of malloc/free do not return freed memory to the operating system (if there is one), but merely make it available for future malloc() calls within the same program. How does free() know how many bytes to free? The malloc/free implementation remembers the size of each block allocated and returned, so it is not necessary to remind it of the size when freeing. So can I query the malloc package to find out how big an allocated block is? Not portably. Is it legal to pass a null pointer as the first argument to realloc()? Why would you want to? ANSI C sanctions this usage (and the related realloc(..., 0), which frees), although several earlier implementations do not support it, so it may not be fully portable. Passing an initially-null pointer to realloc() can make it easier to write a self-starting incremental allocation algorithm. References: ANSI Sec. 4.10.3.4; ISO Sec. 7.10.3.4; H&S Sec. 16.3 p. 388.

A:

7.26: A:

7.27:

A: 7.30:

A:

7.31:

What's the difference between calloc() and malloc()? Is it safe to take advantage of calloc's zero-filling? Does free() work on memory allocated with calloc(), or do you need a cfree()? calloc(m, n) is essentially equivalent to p = malloc(m * n);

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

memset(p, 0, m * n); The zero fill is all-bits-zero, and does *not* therefore guarantee useful null pointer values (see section 5 of this list) or floating-point zero values. free() is properly used to free the memory allocated by calloc(). References: ANSI Sec. 4.10.3 to 4.10.3.2; ISO Sec. 7.10.3 to 7.10.3.2; H&S Sec. 16.1 p. 386, Sec. 16.2 p. 386; PCS Sec. 11 pp. 141,142. 7.32: A: What is alloca() and why is its use discouraged? alloca() allocates memory which is automatically freed when the function which called alloca() returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context. alloca() cannot be written portably, and is difficult to implement on machines without a conventional stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), 100, stdin). For these reasons, alloca() is not Standard and cannot be used in programs which must be widely portable, no matter how useful it might be. See also question 7.22. References: Rationale Sec. 4.10.3.

Section 8. Characters and Strings 8.1: Why doesn't strcat(string, '!');

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

work? A: There is a very real difference between characters and strings, and strcat() concatenates *strings*. Characters in C are represented by small integers corresponding to their character set values (see also question 8.6 below). Strings are represented by arrays of characters; you usually manipulate a pointer to the first character of the array. It is never correct to use one when the other is expected. To append a ! to a string, use strcat(string, "!"); See also questions 1.32, 7.2, and 16.6. References: CT&P Sec. 1.5 pp. 9-10. 8.2: I'm checking a string to see if it matches a particular value. Why isn't this code working? char *string; ... if(string == "value") { /* string matches "value" */ ... } A: Strings in C are represented as arrays of characters, and C never manipulates (assigns, compares, etc.) arrays as a whole. The == operator in the code fragment above compares two pointers -- the value of the pointer variable string and a pointer to the string literal "value" -- to see if they are equal, that is, if they point to the same place. They probably don't, so the comparison never succeeds. To compare two strings, you generally use the library function

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

strcmp(): if(strcmp(string, "value") == 0) { /* string matches "value" */ ... } 8.3: If I can say char a[] = "Hello, world!"; why can't I say char a[14]; a = "Hello, world!"; A: Strings are arrays, and you can't assign arrays directly. strcpy() instead: strcpy(a, "Hello, world!"); See also questions 1.32, 4.2, and 7.2. 8.6: How can I get the numeric (character set) value corresponding to a character, or vice versa? In C, characters are represented by small integers corresponding to their values (in the machine's character set), so you don't need a conversion routine: if you have the character, you have its value. I think something's wrong with my compiler: I just noticed that sizeof('a') is 2, not 1 (i.e. not sizeof(char)). Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though it's different in C++). See also question 7.8. Use

A:

8.9:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: ANSI Sec. 3.1.3.4; ISO Sec. 6.1.3.4; H&S Sec. 2.7.3 p. 29.

Section 9. Boolean Expressions 9.1: What is the right type to use for Boolean values in C? Why isn't it a standard type? Should I use #defines or enums for the true and false values? C does not provide a standard Boolean type, in part because picking one involves a space/time tradeoff which can best be decided by the programmer. (Using an int may be faster, while using char may save data space. Smaller types may make the generated code bigger or slower, though, if they require lots of conversions to and from int.) The choice between #defines and enumeration constants for the true/false values is arbitrary and not terribly interesting (see also questions 2.22 and 17.10). Use any of #define TRUE 1 #define FALSE 0 enum bool {false, true}; #define YES 1 #define NO 0 enum bool {no, yes};

A:

or use raw 1 and 0, as long as you are consistent within one program or project. (An enumeration may be preferable if your debugger shows the names of enumeration constants when examining variables.) Some people prefer variants like #define TRUE (1==1) #define FALSE (!TRUE) or define "helper" macros such as

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#define Istrue(e) ((e) != 0) These don't buy anything (see question 9.2 below; see also questions 5.12 and 10.2). 9.2: Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in logical or relational operator "returns" something other than 1? It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a Boolean value is expected. When a Boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test if((a == b) == TRUE) would work as expected (as long as TRUE is 1), but it is obviously silly. In general, explicit tests against TRUE and FALSE are inappropriate, because some library functions (notably isupper(), isalpha(), etc.) return, on success, a nonzero value which is *not* necessarily 1. (Besides, if you believe that "if((a == b) == TRUE)" is an improvement over "if(a == b)", why stop there? Why not use "if(((a == b) == TRUE) == TRUE)"?) A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable or function parameter, or as the return value from a Boolean function, but never in a comparison. The preprocessor macros TRUE and FALSE (and, of course, NULL) are used for code readability, not because the underlying values might ever change. (See also questions 5.3 and 5.10.) On the other hand, Boolean values and definitions can evidently be confusing, and some programmers feel that TRUE and FALSE macros only compound the confusion. (See also question 5.9.) References: K&R1 Sec. 2.6 p. 39, Sec. 2.7 p. 41; K&R2 Sec. 2.6 p. 42, Sec. 2.7 p. 44, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206;

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

ANSI Sec. 3.3.3.3, Sec. 3.3.8, Sec. 3.3.9, Sec. 3.3.13, Sec. 3.3.14, Sec. 3.3.15, Sec. 3.6.4.1, Sec. 3.6.5; ISO Sec. 6.3.3.3, Sec. 6.3.8, Sec. 6.3.9, Sec. 6.3.13, Sec. 6.3.14, Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5; H&S Sec. 7.5.4 pp. 196-7, Sec. 7.6.4 pp. 207-8, Sec. 7.6.5 pp. 208-9, Sec. 7.7 pp. 217-8, Sec. 7.8 pp. 218-9, Sec. 8.5 pp. 238-9, Sec. 8.6 pp. 241-4; "What the Tortoise Said to Achilles". 9.3: A: Is if(p), where p is a pointer, a valid conditional? Yes. See question 5.3.

Section 10. C Preprocessor 10.2: Here are some cute preprocessor macros: #define begin #define end What do y'all think? A: 10.3: A: Bleah. See also section 17. { }

How can I write a generic macro to swap two values? There is no good answer to this question. If the values are integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers, or if the two values are the same variable (and the "obvious" supercompressed implementation for integral types a^=b^=a^=b is illegal due to multiple side-effects; see question 3.2). If the macro is intended to be used on values of arbitrary type (the usual goal), it cannot use a temporary, since it does not know what type of temporary it needs (and would have a hard time naming it if it did), and standard C does not provide a typeof operator.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The best all-around solution is probably to forget about using a macro, unless you're willing to pass in the type as a third argument. 10.4: A: What's the best way to write a multi-statement macro? The usual goal is to write a macro that can be invoked as if it were a statement consisting of a single function call. This means that the "caller" will be supplying the final semicolon, so the macro body should not. The macro body cannot therefore be a simple brace-enclosed compound statement, because syntax errors would result if it were invoked (apparently as a single statement, but with a resultant extra semicolon) as the if branch of an if/else statement with an explicit else clause. The traditional solution, therefore, is to use #define MACRO(arg1, arg2) do { \ /* declarations */ \ stmt1; \ stmt2; \ /* ... */ \ } while(0) /* (no trailing ; ) */ When the caller appends a semicolon, this expansion becomes a single statement regardless of context. (An optimizing compiler will remove any "dead" tests or branches on the constant condition 0, although lint may complain.) If all of the statements in the intended macro are simple expressions, with no declarations or loops, another technique is to write a single, parenthesized expression using one or more comma operators. (For an example, see the first DEBUG() macro in question 10.26.) This technique also allows a value to be "returned." References: H&S Sec. 3.3.2 p. 45; CT&P Sec. 6.3 pp. 82-3.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

10.6:

I'm splitting up a program into multiple source files for the first time, and I'm wondering what to put in .c files and what to put in .h files. (What does ".h" mean, anyway?) As a general rule, you should put these things in header (.h) files: macro definitions (preprocessor #defines) structure, union, and enumeration declarations typedef declarations external function declarations (see also question 1.11) global variable declarations It's especially important to put a declaration or definition in a header file when it will be shared between several other files. (In particular, never put external function prototypes in .c files. See also question 1.7.) On the other hand, when a definition or declaration should remain private to one source file, it's fine to leave it there. See also questions 1.7 and 10.7. References: K&R2 Sec. 4.5 pp. 81-2; H&S Sec. 9.2.3 p. 267; CT&P Sec. 4.6 pp. 66-7.

A:

10.7: A:

Is it acceptable for one header file to #include another? It's a question of style, and thus receives considerable debate. Many people believe that "nested #include files" are to be avoided: the prestigious Indian Hill Style Guide (see question 17.9) disparages them; they can make it harder to find relevant definitions; they can lead to multiple-definition errors if a file is #included twice; and they make manual Makefile maintenance very difficult. On the other hand, they make it possible to use header files in a modular way (a header file can #include what it needs itself, rather than requiring each #includer to do so); a tool like grep (or a tags file) makes it

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

easy to find definitions no matter where they are; a popular trick along the lines of: #ifndef HFILENAME_USED #define HFILENAME_USED ...header file contents... #endif (where a different bracketing macro name is used for each header file) makes a header file "idempotent" so that it can safely be #included multiple times; and automated Makefile maintenance tools (which are a virtual necessity in large projects anyway; see question 18.1) handle dependency generation in the face of nested #include files easily. See also question 17.10. References: Rationale Sec. 4.1.2. 10.8: A: Where are header ("#include") files searched for? The exact behavior is implementation-defined (which means that it is supposed to be documented; see question 11.33). Typically, headers named with <> syntax are searched for in one or more standard places. Header files named with "" syntax are first searched for in the "current directory," then (if not found) in the same standard places. Traditionally (especially under Unix compilers), the current directory is taken to be the directory containing the file containing the #include directive. Under other compilers, however, the current directory (if any) is the directory in which the compiler was initially invoked. Check your compiler documentation. References: K&R2 Sec. A12.4 p. 231; ANSI Sec. 3.8.2; ISO Sec. 6.8.2; H&S Sec. 3.4 p. 55. 10.9: I'm getting strange syntax errors on the very first declaration in a file, but it looks fine.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Perhaps there's a missing semicolon at the end of the last declaration in the last header file you're #including. See also questions 2.18 and 11.29. Can

10.11: I seem to be missing the system header file . someone send me a copy? A:

Standard headers exist in part so that definitions appropriate to your compiler, operating system, and processor can be supplied. You cannot just pick up a copy of someone else's header file and expect it to work, unless that person is using exactly the same environment. Ask your compiler vendor why the file was not provided (or to send a replacement copy).

10.12: How can I construct preprocessor #if expressions which compare strings? A: You can't do it directly; preprocessor #if arithmetic uses only integers. You can #define several manifest constants, however, and implement conditionals on those. See also question 20.17. References: K&R2 Sec. 4.11.3 p. 91; ANSI Sec. 3.8.1; ISO Sec. 6.8.1; H&S Sec. 7.11.1 p. 225. 10.13: Does the sizeof operator work in preprocessor #if directives? A: No. Preprocessing happens during an earlier phase of compilation, before type names have been parsed. Instead of sizeof, consider using the predefined constants in ANSI's , if applicable, or perhaps a "configure" script. (Better yet, try to write code which is inherently insensitive to type sizes.) References: ANSI Sec. 2.1.1.2, Sec. 3.8.1 footnote 83; ISO Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

10.14: Can I use an #ifdef in a #define line, to define something two different ways? A: No. You can't "run the preprocessor on itself," so to speak. What you can do is use one of two completely separate #define lines, depending on the #ifdef setting. References: ANSI Sec. 3.8.3, Sec. 3.8.3.4; ISO Sec. 6.8.3, Sec. 6.8.3.4; H&S Sec. 3.2 pp. 40-1. 10.15: Is there anything like an #ifdef for typedefs? A: Unfortunately, no. (See also question 10.13.)

References: ANSI Sec. 2.1.1.2, Sec. 3.8.1 footnote 83; ISO Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p. 225. 10.16: How can I use a preprocessor #if expression to tell if a machine is big-endian or little-endian? A: You probably can't. (Preprocessor arithmetic uses only long integers, and there is no concept of addressing. ) Are you sure you need to know the machine's endianness explicitly? Usually it's better to write code which doesn't care ). See also question 20.9. References: ANSI Sec. 3.8.1; ISO Sec. 6.8.1; H&S Sec. 7.11.1 p. 225. 10.18: I inherited some code which contains far too many #ifdef's for my taste. How can I preprocess the code to leave only one conditional compilation set, without running it through the preprocessor and expanding all of the #include's and #define's as well? A: There are programs floating around called unifdef, rmifdef, and scpp ("selective C preprocessor") which do exactly this. See

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

question 18.16. 10.19: How can I list all of the pre#defined identifiers? A: There's no standard way, although it is a common need. If the compiler documentation is unhelpful, the most expedient way is probably to extract printable strings from the compiler or preprocessor executable with something like the Unix strings utility. Beware that many traditional system-specific pre#defined identifiers (e.g. "unix") are non-Standard (because they clash with the user's namespace) and are being removed or renamed.

10.20: I have some old code that tries to construct identifiers with a macro like #define Paste(a, b) a/**/b but it doesn't work any more. A: It was an undocumented feature of some early preprocessor implementations (notably John Reiser's) that comments disappeared entirely and could therefore be used for token pasting. ANSI affirms (as did K&R1) that comments are replaced with white space. However, since the need for pasting tokens was demonstrated and real, ANSI introduced a well-defined tokenpasting operator, ##, which can be used like this: #define Paste(a, b) a##b See also question 11.17. References: ANSI Sec. 3.8.3.3; ISO Sec. 6.8.3.3; Rationale Sec. 3.8.3.3; H&S Sec. 3.3.9 p. 52. 10.22: Why is the macro #define TRACE(n) printf("TRACE: %d\n", n)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

giving me the warning "macro replacement within a string literal"? It seems to be expanding TRACE(count); as printf("TRACE: %d\count", count); A: See question 11.18.

10.23: How can I use a macro argument inside a string literal in the macro expansion? A: See question 11.18.

10.25: I've got this tricky preprocessing I want to do and I can't figure out a way to do it. A: C's preprocessor is not intended as a general-purpose tool. (Note also that it is not guaranteed to be available as a separate program.) Rather than forcing it to do something inappropriate, consider writing your own little special-purpose preprocessing tool, instead. You can easily get a utility like make(1) to run it for you automatically. If you are trying to preprocess something other than C, consider using a general-purpose preprocessor. (One older one available on most Unix systems is m4.) 10.26: How can I write a macro which takes a variable number of arguments? A: One popular trick is to define and invoke the macro with a single, parenthesized "argument" which in the macro expansion becomes the entire argument list, parentheses and all, for a function such as printf(): #define DEBUG(args) (printf("DEBUG: "), printf args)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

if(n != 0) DEBUG(("n is %d\n", n)); The obvious disadvantage is that the caller must always remember to use the extra parentheses. gcc has an extension which allows a function-like macro to accept a variable number of arguments, but it's not standard. Other possible solutions are to use different macros (DEBUG1, DEBUG2, etc.) depending on the number of arguments, to play games with commas: #define DEBUG(args) (printf("DEBUG: "), printf(args)) #define _ , DEBUG("i = %d" _ i) It is often better to use a bona-fide function, which can take a variable number of arguments in a well-defined way. See questions 15.4 and 15.5.

Section 11. 11.1: A:

ANSI/ISO Standard C

What is the "ANSI C Standard?" In 1983, the American National Standards Institute (ANSI) commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, including several widespread public reviews, the committee's work was finally ratified as ANS X3.159-1989 on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardizes existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the controversial trigraph sequences). The ANSI C standard also formalizes the C run-time library support routines. More recently, the Standard has been adopted as an international

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

standard, ISO/IEC 9899:1990, and this ISO Standard replaces the earlier X3.159 even within the United States. Its sections are numbered differently (briefly, ISO sections 5 through 7 correspond roughly to the old ANSI sections 2 through 4). As an ISO Standard, it is subject to ongoing revision through the release of Technical Corrigenda and Normative Addenda. In 1994, Technical Corrigendum 1 amended the Standard in about 40 places, most of them minor corrections or clarifications. More recently, Normative Addendum 1 added about 50 pages of new material, mostly specifying new library functions for internationalization. The production of Technical Corrigenda is an ongoing process, and a second one is expected in late 1995. In addition, both ANSI and ISO require periodic review of their standards. This process is beginning in 1995, and will likely result in a completely revised standard (nicknamed "C9X," on the assumption of completion by 1999). The original ANSI Standard included a "Rationale," explaining many of its decisions, and discussing a number of subtle points, including several of those covered here. (The Rationale was "not part of ANSI Standard X3.159-1989, but... included for information only," and is not included with the ISO Standard.) 11.2: A: How can I get a copy of the Standard? Copies are available in the United States from American National Standards Institute 11 W. 42nd St., 13th floor New York, NY 10036 USA (+1) 212 642 4900 and Global Engineering Documents 15 Inverness Way E Englewood, CO 80112 USA

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(+1) 303 397 2715 (800) 854 7179 (U.S. & Canada) In other countries, contact the appropriate national standards body, or ISO in Geneva at: ISO Sales Case Postale 56 CH-1211 Geneve 20 Switzerland (or see URL http://www.iso.ch or check the comp.std.internat FAQ list, Standards.Faq). At the time of this writing, the cost is $130.00 from ANSI or $410.00 from Global. Copies of the original X3.159 (including the Rationale) may still be available at $205.00 from ANSI or $162.50 from Global. Note that ANSI derives revenues to support its operations from the sale of printed standards, so electronic copies are *not* available. In the U.S., it may be possible to get a copy of the original ANSI X3.159 (including the Rationale) as "FIPS PUB 160" from National Technical Information Service (NTIS) U.S. Department of Commerce Springfield, VA 22161 703 487 4650 The mistitled _Annotated ANSI C Standard_, with annotations by Herbert Schildt, contains most of the text of ISO 9899; it is published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells in the U.S. for approximately $40. It has been suggested that the price differential between this work and the official standard reflects the value of the annotations: they are plagued by numerous errors and omissions, and a few pages of the Standard itself are missing. Many people on the net recommend ignoring the annotations entirely. A review of the annotations

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

("annotated annotations") by Clive Feather can be found on the web at http://www.lysator.liu.se/c/schildt.html . The text of the Rationale (not the full Standard) can be obtained by anonymous ftp from ftp.uu.net (see question 18.16) in directory doc/standards/ansi/X3.159-1989, and is also available on the web at http://www.lysator.liu.se/c/rat/title.html . The Rationale has also been printed by Silicon Press, ISBN 0-929306-07-4. 11.3: My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; { ... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". It is usually safe to mix the two styles (see question 11.4), but not in this case. Old C (and ANSI C, in the absence of prototypes, and in variablelength argument lists; see question 15.2) "widens" certain arguments when they are passed to functions. floats are promoted to double, and characters and short integers are promoted to int. (For old-style function definitions, the values are automatically converted back to the corresponding narrower types within the body of the called function, if they are declared that way there.) This problem can be fixed either by using new-style syntax consistently in the definition: int func(float x) { ... } or by changing the new-style prototype declaration to match the

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

old-style definition: extern int func(double); (In this case, it would be clearest to change the old-style definition to use double as well, as long as the address of that parameter is not taken.) It may also be safer to avoid "narrow" (char, short int, and float) function arguments and return types altogether. See also question 1.25. References: K&R1 Sec. A7.1 p. 186; K&R2 Sec. A7.3.2 p. 202; ANSI Sec. 3.3.2.2, Sec. 3.5.4.3; ISO Sec. 6.3.2.2, Sec. 6.5.4.3; Rationale Sec. 3.3.2.2, Sec. 3.5.4.3; H&S Sec. 9.2 pp. 265-7, Sec. 9.4 pp. 272-3. 11.4: A: Can you mix old-style and new-style function syntax? Doing so is perfectly legal, as long as you're careful (see especially question 11.3). Note however that old-style syntax is marked as obsolescent, so official support for it may be removed some day. References: ANSI Sec. 3.7.1, Sec. 3.9.5; ISO Sec. 6.7.1, Sec. 6.9.5; H&S Sec. 9.2.2 pp. 265-7, Sec. 9.2.5 pp. 269-70. 11.5: Why does the declaration extern f(struct x *p); give me an obscure warning message about "struct x introduced in prototype scope"? A: In a quirk of C's normal block scoping rules, a structure declared (or even mentioned) for the first time within a prototype cannot be compatible with other structures declared in

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

the same source file (it goes out of scope at the end of the prototype). To resolve the problem, precede the prototype with the vacuouslooking declaration struct x; which places an (incomplete) declaration of struct x at file scope, so that all following declarations involving struct x can at least be sure they're referring to the same struct x. References: ANSI Sec. 3.1.2.1, Sec. 3.1.2.6, Sec. 3.5.2.3; ISO Sec. 6.1.2.1, Sec. 6.1.2.6, Sec. 6.5.2.3. 11.8: I don't understand why I can't use const values in initializers and array dimensions, as in const int n = 5; int a[n]; A: The const qualifier really means "read-only;" an object so qualified is a run-time object which cannot (normally) be assigned to. The value of a const-qualified object is therefore *not* a constant expression in the full sense of the term. (C is unlike C++ in this regard.) When you need a true compiletime constant, use a preprocessor #define. References: ANSI Sec. 3.4; ISO Sec. 6.4; H&S Secs. 7.11.2,7.11.3 pp. 226-7. 11.9: What's the difference between "const char *p" and "char * const p"? "char const *p" declares a pointer to a constant character (you can't change the character); "char * const p" declares a constant pointer to a (variable) character (i.e. you can't change the pointer).

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read these "inside out" to understand them; see also question 1.21. References: ANSI Sec. 3.5.4.1 examples; ISO Sec. 6.5.4.1; Rationale Sec. 3.5.4.1; H&S Sec. 4.4.4 p. 81. 11.10: Why can't I pass a char ** to a function which expects a const char **? A: You can use a pointer-to-T (for any type T) where a pointer-toconst-T is expected. However, the rule (an explicit exception) which permits slight mismatches in qualified pointer types is not applied recursively, but only at the top level. You must use explicit casts (e.g. (const char **) in this case) when assigning (or passing) pointers which have qualifier mismatches at other than the first level of indirection. References: ANSI Sec. 3.1.2.6, Sec. 3.3.16.1, Sec. 3.5.3; ISO Sec. 6.1.2.6, Sec. 6.3.16.1, Sec. 6.5.3; H&S Sec. 7.9.1 pp. 2212. 11.12: Can I declare main() as void, to shut off these annoying "main returns no value" messages? A: No. main() must be declared as returning an int, and as taking either zero or two arguments, of the appropriate types. If you're calling exit() but still getting warnings, you may have to insert a redundant return statement (or use some kind of "not reached" directive, if available). Declaring a function as void does not merely shut off or rearrange warnings: it may also result in a different function call/return sequence, incompatible with what the caller (in main's case, the C run-time startup code) expects. (Note that this discussion of main() pertains only to "hosted"

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

implementations; none of it applies to "freestanding" implementations, which may not even have main(). However, freestanding implementations are comparatively rare, and if you're using one, you probably know it. If you've never heard of the distinction, you're probably using a hosted implementation, and the above rules apply.) References: ANSI Sec. 2.1.2.2.1, Sec. F.5.1; ISO Sec. 5.1.2.2.1, Sec. G.5.1; H&S Sec. 20.1 p. 416; CT&P Sec. 3.10 pp. 50-51. 11.13: But what about main's third argument, envp? A: It's a non-standard (though common) extension. If you really need to access the environment in ways beyind what the standard getenv() function provides, though, the global variable environ is probably a better avenue (though it's equally non-standard). References: ANSI Sec. F.5.1; ISO Sec. G.5.1; H&S Sec. 20.1 pp. 416-7. 11.14: I believe that declaring void main() can't fail, since I'm calling exit() instead of returning, and anyway my operating system ignores a program's exit/return status. A: It doesn't matter whether main() returns or not, or whether anyone looks at the status; the problem is that when main() is misdeclared, its caller (the runtime startup code) may not even be able to *call* it correctly (due to the potential clash of calling conventions; see question 11.12). Your operating system may ignore the exit status, and void main() may work for you, but it is not portable and not correct.

11.15: The book I've been using, _C Programing for the Compleat Idiot_, always uses void main(). A: Perhaps its author counts himself among the target audience. Many books unaccountably use void main() in examples. They're wrong.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

11.16: Is exit(status) truly equivalent to returning the same status from main()? A: Yes and no. The Standard says that they are equivalent. However, a few older, nonconforming systems may have problems with one or the other form. Also, a return from main() cannot be expected to work if data local to main() might be needed during cleanup; see also question 16.4. (Finally, the two forms are obviously not equivalent in a recursive call to main().) References: K&R2 Sec. 7.6 pp. 163-4; ANSI Sec. 2.1.2.2.3; ISO Sec. 5.1.2.2.3. 11.17: I'm trying to use the ANSI "stringizing" preprocessing operator `#' to insert the value of a symbolic constant into a message, but it keeps stringizing the macro's name rather than its value. A: You can use something like the following two-step procedure to force a macro to be expanded as well as stringized: #define Str(x) #x #define Xstr(x) Str(x) #define OP plus char *opname = Xstr(OP); This code sets opname to "plus" rather than "OP". An equivalent circumlocution is necessary with the token-pasting operator ## when the values (rather than the names) of two macros are to be concatenated. References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example; ISO Sec. 6.8.3.2, Sec. 6.8.3.5. 11.18: What does the message "warning: macro replacement within a string literal" mean?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Some pre-ANSI compilers/preprocessors interpreted macro definitions like #define TRACE(var, fmt) printf("TRACE: var = fmt\n", var) such that invocations like TRACE(i, %d); were expanded as printf("TRACE: i = %d\n", i); In other words, macro parameters were expanded even inside string literals and character constants. Macro expansion is *not* defined in this way by K&R or by Standard C. When you do want to turn macro arguments into strings, you can use the new # preprocessing operator, along with string literal concatenation (another new ANSI feature): #define TRACE(var, fmt) \ printf("TRACE: " #var " = " #fmt "\n", var) See also question 11.17 above. References: H&S Sec. 3.3.8 p. 51.

11.19: I'm getting strange syntax errors inside lines I've #ifdeffed out. A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that there must be no newlines inside quotes, and no unterminated comments or quotes (note particularly that an apostrophe within a contracted word looks like the beginning of a character constant). Therefore, natural-language comments and pseudocode should always be written between the "official"

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

comment delimiters /* and */. 10.25.)

(But see question 20.20, and also

References: ANSI Sec. 2.1.1.2, Sec. 3.1; ISO Sec. 5.1.1.2, Sec. 6.1; H&S Sec. 3.2 p. 40. 11.20: What are #pragmas and what are they good for? A: The #pragma directive provides a single, well-defined "escape hatch" which can be used for all sorts of implementationspecific controls and extensions: source listing control, structure packing, warning suppression (like lint's old /* NOTREACHED */ comments), etc. References: ANSI Sec. 3.8.6; ISO Sec. 6.8.6; H&S Sec. 3.7 p. 61. 11.21: What does "#pragma once" mean? A: I found it in some header files.

It is an extension implemented by some preprocessors to help make header files idempotent; it is essentially equivalent to the #ifndef trick mentioned in question 10.7. What does it mean?

11.22: Is char a[3] = "abc"; legal? A:

It is legal in ANSI C (and perhaps in a few pre-ANSI systems), though useful only in rare circumstances. It declares an array of size three, initialized with the three characters 'a', 'b', and 'c', *without* the usual terminating '\0' character. The array is therefore not a true C string and cannot be used with strcpy, printf %s, etc. Most of the time, you should let the compiler count the initializers when initializing arrays (in the case of the initializer "abc", of course, the computed size will be 4). References: ANSI Sec. 3.5.7; ISO Sec. 6.5.7; H&S Sec. 4.6.4 p. 98.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

11.24: Why can't I perform arithmetic on a void * pointer? A: The compiler doesn't know the size of the pointed-to objects. Before performing arithmetic, convert the pointer either to char * or to the pointer type you're trying to manipulate (but see also question 4.5). References: ANSI Sec. 3.1.2.5, Sec. 3.3.6; ISO Sec. 6.1.2.5, Sec. 6.3.6; H&S Sec. 7.6.2 p. 204. 11.25: What's the difference between memcpy() and memmove()? A: memmove() offers guaranteed behavior if the source and destination arguments overlap. memcpy() makes no such guarantee, and may therefore be more efficiently implementable. When in doubt, it's safer to use memmove(). References: K&R2 Sec. B3 p. 250; ANSI Sec. 4.11.2.1, Sec. 4.11.2.2; ISO Sec. 7.11.2.1, Sec. 7.11.2.2; Rationale Sec. 4.11.2; H&S Sec. 14.3 pp. 341-2; PCS Sec. 11 pp. 165-6. 11.26: What should malloc(0) do? 0 bytes? A: Return a null pointer or a pointer to

The ANSI/ISO Standard says that it may do either; the behavior is implementation-defined (see question 11.33). References: ANSI Sec. 4.10.3; ISO Sec. 7.10.3; PCS Sec. 16.1 p. 386.

11.27: Why does the ANSI Standard not guarantee more than six caseinsensitive characters of external identifier significance? A: The problem is older linkers which are under the control of neither the ANSI/ISO Standard nor the C compiler developers on the systems which have them. The limitation is only that identifiers be *significant* in the first six characters, not that they be restricted to six characters in length. This

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

limitation is annoying, but certainly not unbearable, and is marked in the Standard as "obsolescent," i.e. a future revision will likely relax it. This concession to current, restrictive linkers really had to be made, no matter how vehemently some people oppose it. (The Rationale notes that its retention was "most painful.") If you disagree, or have thought of a trick by which a compiler burdened with a restrictive linker could present the C programmer with the appearance of more significance in external identifiers, read the excellently-worded section 3.1.2 in the X3.159 Rationale (see question 11.1), which discusses several such schemes and explains why they could not be mandated. References: ANSI Sec. 3.1.2, Sec. 3.9.1; ISO Sec. 6.1.2, Sec. 6.9.1; Rationale Sec. 3.1.2; H&S Sec. 2.5 pp. 22-3. 11.29: My compiler is rejecting the simplest possible test programs, with all kinds of syntax errors. A: Perhaps it is a pre-ANSI compiler, unable to accept function prototypes and the like. See also questions 1.31, 10.9, and 11.30. 11.30: Why are some ANSI/ISO Standard library routines showing up as undefined, even though I've got an ANSI compiler? A: It's possible to have a compiler available which accepts ANSI syntax, but not to have ANSI-compatible header files or run-time libraries installed. (In fact, this situation is rather common when using a non-vendor-supplied compiler such as gcc.) See also questions 11.29, 13.25, and 13.26.

11.31: Does anyone have a tool for converting old-style C programs to ANSI C, or vice versa, or for automatically generating prototypes?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Two programs, protoize and unprotoize, convert back and forth between prototyped and "old style" function definitions and declarations. (These programs do *not* handle full-blown translation between "Classic" C and ANSI C.) These programs are part of the FSF's GNU C compiler distribution; see question 18.3. The unproto program (/pub/unix/unproto5.shar.Z on ftp.win.tue.nl) is a filter which sits between the preprocessor and the next compiler pass, converting most of ANSI C to traditional C on-the-fly. The GNU GhostScript package comes with a little program called ansi2knr. Before converting ANSI C back to old-style, beware that such a conversion cannot always be made both safely and automatically. ANSI C introduces new features and complexities not found in K&R C. You'll especially need to be careful of prototyped function calls; you'll probably need to insert explicit casts. See also questions 11.3 and 11.29. Several prototype generators exist, many as modifications to lint. A program called CPROTO was posted to comp.sources.misc in March, 1992. There is another program called "cextract." Many vendors supply simple utilities like these with their compilers. See also question 18.16. (But be careful when generating prototypes for old functions with "narrow" parameters; see question 11.3.) Finally, are you sure you really need to convert lots of old code to ANSI C? The old-style function syntax is still acceptable, and a hasty conversion can easily introduce bugs. (See question 11.3.)

11.32: Why won't the Frobozz Magic C Compiler, which claims to be ANSI compliant, accept this code? I know that the code is ANSI, because gcc accepts it.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Many compilers support a few non-Standard extensions, gcc more so than most. Are you sure that the code being rejected doesn't rely on such an extension? It is usually a bad idea to perform experiments with a particular compiler to determine properties of a language; the applicable standard may permit variations, or the compiler may be wrong. See also question 11.35.

11.33: People seem to make a point of distinguishing between implementation-defined, unspecified, and undefined behavior. What's the difference? A: Briefly: 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: ANSI Sec. 1.6; 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

undefined. things? A:

Isn't a Standard's whole job to standardize these

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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 passing getchar's return value through 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; ANSI Sec. 3.1.2.5, Sec. 4.9.1, Sec. 4.9.7.5; ISO Sec. 6.1.2.5, Sec. 7.9.1, Sec. 7.9.7.5; 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, EOF is only indicated *after* an input routine has tried to read, and has reached end-of-file. (In other words, C's I/O is not like Pascal's.) Usually, you should just check the return value of the input routine (fgets() in this case); often, you don't need to use feof() at all. References: K&R2 Sec. 7.6 p. 164; ANSI Sec. 4.9.3, Sec. 4.9.7.1, Sec. 4.9.10.2; ISO Sec. 7.9.3, Sec. 7.9.7.1, Sec. 7.9.10.2; H&S Sec. 15.14 p. 382.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. It's best to use an explicit fflush(stdout) whenever output should definitely be visible. Several mechanisms attempt to perform the fflush() for you, at the "right time," but they tend to apply only when stdout is an interactive terminal. (See also question 12.24.) References: ANSI Sec. 4.9.5.2; ISO Sec. 7.9.5.2.

A:

12.5:

How can I read one character at a time, without waiting for the RETURN key? See question 19.1. How can I print a '%' character in a printf format string? tried \%, but it didn't work. 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 printf's escape character. See also question 19.17. References: K&R1 Sec. 7.3 p. 147; K&R2 Sec. 7.2 p. 154; ANSI Sec. 4.9.6.1; ISO Sec. 7.9.6.1. I

A: 12.6:

A:

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? 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

type float are promoted to double, and printf() therefore sees only doubles. 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; ANSI Sec. 4.9.6.1, Sec. 4.9.6.2; ISO Sec. 7.9.6.1, Sec. 7.9.6.2; H&S Sec. 15.8 pp. 357-64, Sec. 15.11 pp. 366-78; CT&P Sec. A.1 pp. 121-33. 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, n) will do just what you want. question 12.15. See also

References: K&R1 Sec. 7.3; K&R2 Sec. 7.2; ANSI Sec. 4.9.6.1; ISO Sec. 7.9.6.1; 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 routines in 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: ANSI Sec. 4.4; 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);

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 to construct a scanf format string on-the-fly.

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; ANSI Sec. 4.9.6.2; ISO Sec. 7.9.6.2; 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: ANSI Sec. 4.9.6.2; ISO Sec. 7.9.6.2; 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: ANSI Sec. 4.9.6.2; ISO Sec. 7.9.6.2; H&S Sec. 15.8 pp. 357-64. 12.20: Why does everyone say not to use scanf()? instead? A: What should I use

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

techniques. (Routines like strtol(), strtok(), and atoi() are often useful; see also question 13.6.) If you do use sscanf(), don't forget to check the return value to make sure that the expected number of items were found. 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: There are not (yet) any good answers to either of these excellent questions, and this represents perhaps the biggest deficiency in the traditional stdio library. When the format string being used with sprintf() is known and relatively simple, you can usually 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. You can conservatively estimate the size that %d will expand to with code like: #include char buf[(sizeof(int) * CHAR_BIT + 2) / 3 + 1 + 1]; sprintf(buf, "%d", n); (This code computes the number of characters required for a base8 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

value or the size of the file (but see question 19.12). 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. Several stdio's (including GNU and 4.4bsd) provide the obvious snprintf() function, which can be used like this: snprintf(buf, bufsize, "You typed \"%s\"", answer); and we can hope that a future revision of the ANSI/ISO C Standard will include this function. 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. 4.9.7.2; 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.) References: ANSI Sec. 4.1.3, Sec. 4.9.10.3; ISO Sec. 7.1.4, Sec. 7.9.10.3; CT&P Sec. 5.4 p. 73; PCS Sec. 14 p. 254. 12.25: What's the difference between fgetpos/fsetpos and ftell/fseek?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

What are fgetpos() and fsetpos() good for? A: fgetpos() and fsetpos() use a special typedef, fpos_t, for representing offsets (positions) in a file. The type behind this typedef, if chosen appropriately, can represent arbitrarily large offsets, allowing fgetpos() and fsetpos() to be used with arbitrarily huge files. ftell() and fseek(), on the other hand, use long int, and are therefore limited to offsets which can be represented in a long int. See also question 1.4. References: K&R2 Sec. B1.6 p. 248; ANSI Sec. 4.9.1, Secs. 4.9.9.1,4.9.9.3; ISO Sec. 7.9.1, Secs. 7.9.9.1,7.9.9.3; 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 be sufficient unread characters can also accumulate in other, OS-level input buffers. References: ANSI Sec. 4.9.5.2; ISO Sec. 7.9.5.2; 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; see also question 19.14.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: ANSI Sec. 4.9.5.3; ISO Sec. 7.9.5.3. 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: ANSI Sec. 4.9.5.4; ISO Sec. 7.9.5.4; 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.

12.38: How can I read a binary data file properly? I'm occasionally seeing 0x0a and 0x0d values getting garbled, and it seems 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: ANSI Sec. 4.9.5.3; ISO Sec. 7.9.5.3; H&S Sec. 15.2.1 p. 348.

Section 13. Library Functions

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

13.1:

How can I convert numbers to strings (the opposite of atoi)? there an itoa function? 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.5; see also question 12.21. You can obviously use sprintf() to convert long or floatingpoint numbers to strings as well (using %ld or %f). References: K&R1 Sec. 3.6 p. 60; K&R2 Sec. 3.6 p. 64.

Is

A:

13.2:

Why does strncpy() not always place a '\0' terminator in the destination string? 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 routine to use than strncpy().

A:

13.5:

Why do some versions of toupper() act strangely if given an upper-case letter? Why does some code call islower() before toupper()? 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).

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

In ANSI/ISO Standard C, these functions are guaranteed to work appropriately on all character arguments. References: ANSI Sec. 4.3.2; 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? The only Standard routine 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; ANSI Sec. 4.11.5.8; ISO Sec. 7.11.5.8; H&S Sec. 13.7 pp. 333-4; PCS p. 178. 13.7: A: I need some code to do regular expression and wildcard matching. 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 or , and functions called regcmp()/regex(), regcomp()/regexec(), or re_comp()/re_exec(). (These functions may exist in a separate regexp library.) A popular, freelyredistributable 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 13.8: I'm trying to sort an array of strings with qsort(), using strcmp() as the comparison function, but it's not working. 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" (char **) and dereferenced, yielding char *'s which can be passed to strcmp(). (Under a pre-ANSI compiler, declare the pointer parameters as char * instead of void *, and drop the consts.) (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: ANSI Sec. 4.10.5.2; ISO Sec. 7.10.5.2; H&S Sec. 20.5 p. 419.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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. Explicit casts, and char * pointers, would be required under a pre-ANSI compiler. See also question 7.7.) If, on the other hand, you're sorting pointers to structures, you'll need indirection, as in question 13.8: sp1 = *(struct mystruct **)p1 . In general, it is a bad idea to insert casts just to "shut the compiler up." 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: ANSI Sec. 4.10.5.2; ISO Sec. 7.10.5.2; H&S Sec. 20.5 p. 419.

A:

13.10: How can I sort a linked list? A: Sometimes it's easier to keep the list in order as you build it

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(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, and/or localtime functions. (These routines have been around for years, and are in the ANSI standard.) Here is a simple example: #include #include main() { time_t now; time(&now); printf("It's %.24s.\n", ctime(&now)); return 0;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

} References: K&R2 Sec. B10 pp. 255-7; ANSI Sec. 4.12; ISO Sec. 7.12; H&S Sec. 18. 13.13: I know that the library routine localtime() will convert a time_t into a broken-down struct tm, and that ctime() will convert a time_t to a printable string. How can I perform the inverse operations of converting a struct tm or a string into a time_t? A: ANSI C specifies a library routine, mktime(), which converts a struct tm to a time_t. 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 routines 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; ANSI Sec. 4.12.2.3; ISO Sec. 7.12.2.3; H&S Sec. 18.4 pp. 401-2. 13.14: How can I add N days to a date? between two dates? A: How can I find the difference

The ANSI/ISO Standard C mktime() and difftime() functions provide some support for both problems. mktime() accepts nonnormalized 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. Another approach to both problems is to use "Julian day" numbers. Implementations of Julian day routines can be found in the file JULCAL10.ZIP from the Simtel/Oakland archives (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; ANSI Secs. 4.12.2.2,4.12.2.3; ISO Secs. 7.12.2.2,7.12.2.3; H&S Secs. 18.4,18.5 pp. 401-2; David Burki, "Date Conversions". 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; ANSI Sec. 4.10.2.1; ISO Sec. 7.10.2.1; 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 */

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(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 ), 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

attempt to get "really random" numbers.) References: K&R2 Sec. 7.8.7 p. 168; ANSI Sec. 4.10.2.2; ISO Sec. 7.10.2.2; 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. 3.2.1.1 pp. 12-14. 13.20: How can I generate random numbers with a normal or Gaussian distribution? A: Here is one method, by Box and Muller, and recommended by Knuth: #include #include 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);

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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; Box and Muller, "A Note on the Generation of Random Normal Deviates"; Press et al., _Numerical Recipes in C_ Sec. 7.2 pp. 288-290. 13.24: I'm trying to port this old program. Why do I get "undefined external" errors for: index? rindex? bcopy? A: Those routines are variously obsolete; you should instead:

bcmp? bzero?

use strchr. use strrchr. use memmove, after interchanging the first and second arguments (see also question 11.25). use memcmp. use memset, with a second argument of 0.

Contrariwise, if you're using an older system which is missing the functions in the second column, you may be able to implement them in terms of, or substitute, the functions in the first. References: PCS Sec. 11.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

13.25: I keep getting errors due to library functions being undefined, but I'm #including all the right header files. A: In some cases (especially if the functions are nonstandard) you may have to explicitly ask for the correct libraries to be searched when you link the program. 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 only get an error about _end being undefined when other things 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? Most computers use base 2 for floating-point numbers as well as for integers. In base 2, 1/1010 (that is, 1/10 decimal) is an infinitely-repeating fraction: its binary representation is 0.0001100110011... . Depending on how carefully your compiler's

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. Make sure that you have #included , and correctly declared other functions returning double. (Another library routine to be careful with is atof(), which is declared in .) 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 , but I keep getting "undefined: sin" compilation errors. Make sure instance, the *end* questions you're actually linking with the math library. For under Unix, you usually need to use the -lm option, at of the command line, when compiling/linking. See also 13.25 and 13.26.

A:

A:

14.4:

My floating-point calculations are acting strangely and giving me different answers on different machines. 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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) use something like #include if(fabs(a - b) <= epsilon * a)

A:

/* WRONG */

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

for some suitably-chosen epsilon. References: Knuth Sec. 4.2.2 pp. 217-8. 14.6: A: How do I round numbers? The simplest and most straightforward way is with code like (int)(x + 0.5) This technique won't work properly for negative numbers, though. 14.7: A: Why doesn't C have an exponentiation operator? Because few processors have an exponentiation instruction. has a pow() function, declared in , although explicit multiplication is often better for small positive integral exponents. C

References: ANSI Sec. 4.5.5.1; ISO Sec. 7.5.5.1; H&S Sec. 17.6 p. 393. 14.8: The pre-#defined constant M_PI seems to be missing from my machine's copy of . 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. References: PCS Sec. 13 p. 237. 14.9: A: How do I test for IEEE NaN and other special values? Many systems with high-quality IEEE floating-point implementations provide facilities (e.g. predefined constants, and functions like isnan(), either as nonstandard extensions in or perhaps in or ) to deal with these

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 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. 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. See also questions 2.7, 2.10, and 14.12.

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 maintains an index of free numerical software; it is posted periodically, and available where this FAQ list is archived (see question 20.40). See also question 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: The message in the question has to do with an indecent problem in Borland's compilers, which for some unfathomable reason has still not been fixed. However, by the newly-passed Communications Decency Act of the U.S., I am prohibited from transmitting or discussing "indecent" material. (If the fact that users of Borland's compilers are still having this problem

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

isn't indecent, I don't know what is.) If you send me e-mail certifying that you are over 18 years of age, I may be able to help you. (You may also be able to 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 printf(). Why? before calling

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: ANSI Sec. 3.3.2.2, Sec. 4.1.6; ISO Sec. 6.3.2.2, Sec. 7.1.7; Rationale Sec. 3.3.2.2, 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? 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.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: ANSI Sec. 3.3.2.2; ISO Sec. 6.3.2.2; 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? Use the facilities of the header.

A:

Here is a function which concatenates an arbitrary number of strings into malloc'ed memory: #include #include #include /* for malloc, NULL, size_t */ /* for va_ stuff */ /* for strcat et al. */

char *vstrcat(char *first, ...) { size_t len; char *retbuf; va_list argp;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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); if(retbuf == NULL) return NULL; (void)strcpy(retbuf, first); va_start(argp, first); /* restart for second scan */ /* +1 for trailing \0 */

/* error */

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.)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Under a pre-ANSI compiler, rewrite the function definition without a prototype ("char *vstrcat(first) char *first; {"), include rather than , add "extern char *malloc();", and use int instead of size_t. You may also have to delete the (void) casts, and use the older varargs package instead of stdarg. See also question 15.7. References: K&R2 Sec. 7.3 p. 155, Sec. B7 p. 254; ANSI Sec. 4.8; 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? Use vprintf(), vfprintf(), or vsprintf(). Here is an error() routine which prints an error message, preceded by the string "error: " and terminated with a newline: #include #include 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; ANSI Secs. 4.9.6.7,4.9.6.8,4.9.6.9; ISO

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Secs. 7.9.6.7,7.9.6.8,7.9.6.9; 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? Unfortunately, vscanf and the like are not standard. your own. I have a pre-ANSI compiler, without . What can I do? You're on

A:

15.7: A:

There's an older header, , which offers about the same functionality. To rewrite the error() function from question 15.5 to use , change the function header to: void error(va_alist) va_dcl { char *fmt; change the va_start line to va_start(argp); and add the line fmt = va_arg(argp, char *); between the calls to va_start and vfprintf. no semicolon after va_dcl.) (Note that there is

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?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 generate). 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(). References: ANSI Sec. 3.5.4, Sec. 3.5.4.3, Sec. 4.8.1.1; ISO Sec. 6.5.4, Sec. 6.5.4.3, Sec. 7.8.1.1; H&S Sec. 9.2 p. 263.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

15.10: I have a varargs function which accepts a float parameter. isn't va_arg(argp, float) working? A:

Why

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. See also questions 11.3 and 15.2. References: ANSI Sec. 3.3.2.2; ISO Sec. 6.3.2.2; Rationale Sec. 4.8.1.2; H&S Sec. 11.4 p. 297.

15.11: I can't get va_arg() to pull in an argument of type pointer-tofunction. A: The type-rewriting games which the va_arg() macro typically plays are stymied by overly-complicated types such as pointer-tofunction. If you use a typedef for the function pointer type, however, all will be well. See also question 1.21. References: ANSI Sec. 4.8.1.2; ISO Sec. 7.8.1.2; Rationale Sec. 4.8.1.2. 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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.3: This program crashes before it even runs! (When single-stepping with a debugger, it dies before the first statement in main().) 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.12, 16.4, 16.5, and 18.4.)

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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.5 and 11.16. References: CT&P Sec. 5.3 pp. 72-3.

A:

16.5:

This program runs perfectly on one machine, but I get weird results on another. Stranger still, adding or removing debugging printouts changes the symptoms... 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 (see questions 1.25 and 14.2) dereferenced null pointers (see section 5) improper malloc/free use: assuming malloc'ed memory contains 0, assuming freed storage persists, freeing something twice (see also questions 7.20 and 7.19) pointer problems in general (see also question 16.8)

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

mismatch between printf() format and arguments, especially trying to print long ints using %d (see question 12.9) trying to malloc(256 * 256 * sizeof(double)), 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: ANSI Sec. 3.1.4; ISO Sec. 6.1.4; H&S Sec. 2.7.4 pp. 31-2. 16.8: A: What do "Segmentation violation" and "Bus error" mean? These generally mean that your program tried to access memory it shouldn't have, invariably as a result of improper pointer use. Likely causes are 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: A: What's the best style for code layout in C? 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. A better option is to use a macro: #define Streq(s1, s2) (strcmp((s1), (s2)) == 0) Opinions on code style, like those on religion, can be debated endlessly. Though good style is a worthy goal, and can usually be recognized, it cannot be rigorously codified. See also question 17.10. 17.4: A: Why do some people write if(0 == x) instead of if(x == 0)? 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

if(0 = x) Evidently it can be easier to remember to reverse the test than it is to remember to type the doubled = sign. 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? 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: A: What is "Hungarian Notation"? Is it worthwhile?

A:

Hungarian Notation is a naming convention, invented by Charles Simonyi, which encodes things 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?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Various documents are available for anonymous ftp from: Site: cs.washington.edu File or directory: pub/cstyle.tar.Z (the updated Indian Hill guide) doc/programming (including Henry Spencer's "10 Commandments for C Programmers") pub/style-guide

ftp.cs.toronto.edu

ftp.cs.umd.edu

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. (The _Standards and Guidelines_ book is not in fact a style guide, but a set of guidelines on selecting and creating style guides.) 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: cflow, cxref, calls, cscope, xscope, or ixfw cb, indent, GNU indent, or vgrind RCS or SCCS

a C cross-reference generator a C beautifier/prettyprinter a revision control or configuration management tool a C source obfuscator (shrouder) a "make" dependency generator tools to compute code metrics

obfus, shroud, or opqcp

makedepend, or try cc -M or cpp -M ccount, Metre, lcount, or csize, or see URL http://www.qucis.queensu.ca:1999/SoftwareEngineering/Cmetrics.html ;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

there is also a package sold by McCabe and Associates a C lines-of-source counter this can be done very crudely with the standard Unix utility wc, and considerably better with grep -c ";" see question 11.31

a prototype generator a tool to track down malloc problems a "selective" C preprocessor language translation tools C verifiers (lint) a C compiler!

see question 18.2

see question 10.18 see questions 11.31 and 20.26 see question 18.7 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.16 and 18.3. 18.2: A: How can I track down these pesky malloc problems? 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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, 603-889-2386. CodeCenter (formerly Saber-C) from Centerline Software (formerly Saber), 10 Fawcett Street, Cambridge, MA 02138-1110, USA, 617-498-3000. Insight, from ParaSoft Corporation, 2500 E. Foothill Blvd., Pasadena, CA 91107, USA, 818-792-9941, insight@parasoft.com . Purify, from Pure Software, 1309 S. Mary Ave., Sunnyvale, CA 94087, USA, 800-224-7873, info-home@pure.com . SENTINEL, from AIB Software, 46030 Manekin Plaza, Dulles, VA 20166, USA, 703-430-9247, 800-296-3000, info@aib.com . 18.3: A: What's a free or cheap C compiler I can use? 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; it can be found in the Simtel and Oakland archives and probably many others, usually in a directory like pub/msdos/djgpp/ or simtel/msdos/djgpp/. There is a shareware compiler called PCC, available as PCC12C.ZIP .

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A very inexpensive MS-DOS compiler is Power C from Mix Software, 1132 Commerce Drive, Richardson, TX 75801, USA, 214-783-6001. Another recently-developed compiler is lcc, available for anonymous ftp from ftp.cs.princeton.edu in pub/lcc. 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/compilerslist/. (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. you see anything wrong with it? Can

A:

See if you can run lint first (perhaps with the -a, -c, -h, -p or other options). Many C compilers are really only halfcompilers, electing not to diagnose numerous source code difficulties which would not actively preclude code generation. See also questions 16.5 and 16.8. 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()? 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#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: A: Where can I get an ANSI-compatible lint? 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 (+1) 610 584 4261 gimpel@netaxs.com

USA

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 higherlevel 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. 18.8: A: Don't ANSI function prototypes render lint obsolete? Not really. 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,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: A: Are there any C tutorials or other resources on the net? There are several of them: "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 svrftp.eng.cam.ac.uk in the misc directory. An html version is at http://club.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/. 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 . Finally, on some Unix machines you can try typing learn c at the shell prompt. [Disclaimer: I have not reviewed these tutorials; I have heard that at least one of them contains a number of errors. Also, this sort of information rapidly becomes out-of-date; these addresses may not work by the time you read this and try them.]

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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://vinny.csd.mu.edu/ . See also question 18.10 below. 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. 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/. This FAQ list's editor maintains a collection of previous answers to this question, which is available upon request. also question 18.9 above. 18.13: Where can I find the sources of the standard C libraries?

See

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 question 18.16.

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 ("Cminus-minus" or "C minus the hard stuff"). See also question 18.16. 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 . 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. 234239; ANSI Sec. A.2; ISO Sec. B.2; H&S pp. 423-435 Appendix B.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

18.15a: Does anyone have a C compiler test suite I can use? A: Plum Hall (formerly in Cardiff, NJ; now in Hawaii) sells one; another package is Ronald Guilmette's RoadTest(tm) Compiler Test Suites (ftp to netcom.com, pub/rfg/roadtest/announce.txt for information). The FSF's GNU C (gcc) distribution includes a ctorture-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.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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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": for any program or resource available on the net, if you know its name, an archie server can usually tell you which anonymous ftp sites have it. Your system may have an archie command, or you can send the mail message "help" to archie@archie.cs.mcgill.ca for information. 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. 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 question 14.12. 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? 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.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 lineat-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, batchoriented mainframes) perform input processing in peripheral processors which cannot be told to do anything other than lineat-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 topics that C does deal with, you will usually get better answers to these 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Note that the answers are often not unique even across different variants of a system; bear in mind when answering systemspecific 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 and tty(4) under classic versions, and termio(4) under System V, or and termios(4) under POSIX.) Under MSDOS, 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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. How can I display a percentage-done indication that updates itself in place, or show one of those "twirling baton" progress indicators? 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: ANSI Sec. 2.2.2; ISO Sec. 5.2.2. 19.4: How can I clear the screen? How can I print things in inverse video? How can I move the cursor to a specific x, y position? 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.

A:

19.3:

A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 would 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: A: How do I read the arrow keys? What about function keys?

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 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: A:

How do I read the mouse? Consult your system documentation, or ask on system-specific newsgroup (but check its FAQ handling is completely different under the X DOS, the Macintosh, and probably every other References: PCS Sec. 5.5 pp. 78-80. an appropriate list first). Mouse window system, MSsystem.

19.7:

How can I do serial ("comm") port I/O?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. How can I direct output to the printer? 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.8: A:

19.9:

How do I send escape sequences to control a terminal or other device? 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 .

A:

19.10: How can I do graphics? A: Once upon a time, Unix had a fairly nice little set of deviceindependent plot routines described in plot(3) and plot(5), but they've largely fallen into disuse. If you're programming for MS-DOS, you'll probably want to use

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 Ccallable 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? if a requested input file is missing. A: I want to warn the user

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 routines are stat(), access(), and fopen(). (To make an approximate test for file existence with fopen(), just open for reading and close immediately.) 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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(), but these tend to have the same 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 routines called filesize() or filelength(), but these are 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: ANSI Sec. 4.9.9.4; ISO Sec. 7.9.9.4; H&S Sec. 15.5.1; PCS Sec. 12 p. 213; POSIX Sec. 5.6.2. 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

records, you might consider simply marking them as deleted, to avoid rewriting.) 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 when 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; ANSI Sec. 4.9.4.1; ISO Sec. 7.9.4.1; H&S Sec. 15.15 p. 382; PCS Sec. 12 pp. 208,220221; POSIX Sec. 5.5.1, Sec. 8.2.4. 19.17: Why can't I open a file by its explicit path? 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 The call

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 routine) 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 actually 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() routines, 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 a single object can be larger than 32K.) Often it's a good idea to use data structures which don't require that all memory be contiguous. For dynamicallyallocated 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 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: ANSI Sec. 2.2.4.1; ISO Sec. 5.2.4.1.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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; ANSI Sec. 3.3.4; 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Note that system's return value is the command's exit status, 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; ANSI Sec. 4.10.4.5; ISO Sec. 7.10.4.5; 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() routine, 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; ANSI

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Sec. 2.1.2.2.1; ISO Sec. 5.1.2.2.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. 19.36: How can I read in an object file and jump to routines 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

19.37: How can I implement a delay, or time a user's response, with subsecond resolution? A: Unfortunately, there is no portable way. V7 Unix, and derived systems, provided a fairly useful ftime() routine 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(), setitimer(), sleep(), times(), and usleep(). (A routine 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 MSDOS 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 if CLOCKS_PER_SEC is greater than 1, the difference will have subsecond resolution. 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, singletasking machine as it is terribly antisocial to any other processes. Under a multi-tasking 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++) ;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

but resist this temptation if at all possible! For one thing, your carefully-calculated delay loops will stop working 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,2156; 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(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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: ANSI Secs. 4.7,4.7.1; 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 routine matherr() which will be called when there are certain floating-point errors, such as errors in the math routines in . 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? applications? A: Do networking? Write client/server

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.) How can I write ISR's? How can I

19.40b: How do I use BIOS calls? 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

resource is Ralf Brown's interrupt list. 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. (POSIX defines a few.) 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: A: How can I return multiple values from a function? 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.5. How do I access command-line arguments? They are pointed to by the argv array with which main() is called. References: K&R1 Sec. 5.11 pp. 110-114; K&R2 Sec. 5.10 pp. 114118; ANSI Sec. 2.1.2.2.1; ISO Sec. 5.1.2.2.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? The most portable solution is to use text files (usually ASCII), written with fprintf() and read with fscanf() or the like.

20.3: A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(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? 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 and 19.36. References: PCS Sec. 11 p. 168. 20.8: A: How can I implement sets or arrays of bits? 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

use with arrays of char: #include #define #define #define #define /* for CHAR_BIT */ BITMASK(b) (1 << ((b) % CHAR_BIT)) BITSLOT(b) ((b) / CHAR_BIT) BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b)) BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))

(If you don't have , 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? 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.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. During *binary* I/O, however, the base again becomes immaterial. For more information about "binary" I/O, see question 2.11. also questions 8.6 and 13.1. References: ANSI Secs. 4.10.1.5,4.10.1.6; ISO Secs. 7.10.1.5,7.10.1.6. 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

20.12: What is the most efficient way to count the number of bits which are set in a value? 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: How can I make my code more efficient? A: Efficiency, though a favorite comp.lang.c topic, is not important nearly as often as people tend to think it is. Most of the code in most programs is not time-critical. When code is not time-critical, it is far more important that it be written clearly and portably than that it be written maximally efficiently. (Remember that computers are very, very fast, and that even "inefficient" code can run without apparent delay.) It is notoriously difficult to predict what the "hot spots" in a program will be. When efficiency is a concern, it is important

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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, it is not as important to "microoptimize" the coding details. Many of the "efficient coding tricks" which are frequently suggested (e.g. substituting shift operators for multiplication by powers of two) are performed automatically by even simpleminded compilers. Heavyhanded optimization attempts can make code so bulky that performance is 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Function calls, though obviously incrementally slower than inline 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.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; ANSI Sec. 3.6.4.2; ISO Sec. 6.6.4.2; 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 questions question 20.17. References: K&R1 Sec. 3.4 p. 55; K&R2 Sec. 3.4 p. 58; ANSI

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Sec. 3.6.4.2; ISO Sec. 6.6.4.2; Rationale Sec. 3.6.4.2; 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, as long as its operand is a variable or a unary expression.) References: K&R1 Sec. A18.3 p. 218; ANSI Sec. 3.3.3, Sec. 3.6.6; 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 doublequoted 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 currently 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; ANSI

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Sec. 3.1.9 (esp. footnote 26), Appendix E; 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.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 when such functions must communicate is to pass around a pointer to a structure containing the necessary context.)

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 (131.169.2.244). In C++, a "C" modifier in an external function declaration indicates that the function is to be called using C calling conventions.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 . Another Pascal to C converter, this one written in Pascal (comp.sources.unix, Volume 10, also patches in Volume 13?). 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 netlib@research.att.com or research!netlib. (It is also available via anonymous ftp on netlib.att.com, in directory netlib/f2c.)

ptoc

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? code? A: Can I use a C++ compiler to compile C

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. In spite of the differences, many C programs will compile correctly in a C++ environment, and

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

many recent compilers offer both C and C++ compilation modes. 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 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: dayofweek(y, m, d) /* 0 = Sunday */ int y, m, d; /* 1 <= m <= 12, y > 1752 or so */ { 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: ANSI Sec. 4.12.2.3; ISO Sec. 7.12.2.3. 20.32: Will 2000 be a leap year? for leap years? A: Yes and no, respectively. Gregorian calendar is Is (year % 4 == 0) an accurate test

The full expression for the present

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.) 20.34: Here's a good puzzle: how do you write a program which produces its own source code as its 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Here is a classic example (which is normally 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, assumes that the doublequote 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 memorymapped 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,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 schedule is tied to the dates of the USENIX conferences at which the winners are announced. At the time of this writing, it is expected that the yearly contest will open in October. To obtain a current copy of the rules and guidelines, send e-mail with the Subject: line "send rules" to: {apple,pyramid,sun,uunet}!hoptoad!judges judges@toad.com or

(Note that these are *not* the addresses for submitting entries.) Contest winners should be announced at the winter USENIX conference in January, 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/. As a last resort, previous winners may be obtained by sending email to the above address, using the Subject: "send YEAR winners", where YEAR is a single four-digit year, a year range, or "all". 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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;" the choice is arbitrary. What about back

20.40: Where can I get extra copies of this list? 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/). An archie

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

server (see question 18.16) should help you find others; ask it to "find 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 mail-server@rtfm.mit.edu . See the metaFAQ 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 . URL's pointing at all FAQ lists (these may also allow topic searching) are http://www.cis.ohiostate.edu/hypertext/faq/usenet/FAQ-List.html and http://www.luth.se/wais/ . An extended version of this FAQ list is being published by Addison-Wesley as _C Programming FAQs: Frequently Asked Questions_ (ISBN 0-201-84519-9). It should be available in November 1995. This list is an evolving document of questions which have been Frequent since before the Great Renaming, 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 Americal National Standards Institute, _American National Standard for Information Systems -- Programming Language -- C_, ANSI X3.159-1989 (see question 11.2). [ANSI] Americal 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 013-970244-X.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

G.E.P. Box and Mervin E. Muller, "A Note on the Generation of Random Normal Deviates," _Annals of Mathematical Statistics_, Vol. 29 #2, June, 1958, pp. 610-611. 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 0937175-30-7. David Goldberg, "What Every Computer Scientist Should Know about Floating-Point Arithmetic," _ACM Computing Surveys_, Vol. 23 #1, March, 1991, pp. 5-48. Samuel P. Harbison and Guy L. Steele, Jr., _C: A Reference Manual_, Fourth Edition, Prentice-Hall, 1995, ISBN 0-13-326224-3. [H&S] Mark R. Horton, _Portable C Software_, Prentice Hall, 1990, ISBN 0-13868050-7. [PCS] Institute of Electrical and Electronics Engineers, _Portable Operating System Interface (POSIX) -- Part 1: System Application Program Interface (API) [C Language_, IEEE Std. 1003.1, ISO/IEC 9945-1. International Organization for Standardization, ISO 9899:1990 (see question 11.2). [ISO] Brian W. Kernighan and P.J. Plauger, _The Elements of Programming Style_, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5. Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_, Prentice-Hall, 1978, ISBN 0-13-110163-3. [K&R1] Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_, Second Edition, Prentice Hall, 1988, ISBN 0-13-110362-8, 0-13-110370-9. [K&R2] Donald E. Knuth, _The Art of Computer Programming_. Volume 1:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

_Fundamental Algorithms_, Second Edition, Addison-Wesley, 1973, ISBN 0201-03809-9. Volume 2: _Seminumerical Algorithms_, Second Edition, Addison-Wesley, 1981, ISBN 0-201-03822-6. Volume 3: _Sorting and Searching_, Addison-Wesley, 1973, ISBN 0-201-03803-X. [Knuth] Andrew Koenig, _C Traps and Pitfalls_, Addison-Wesley, 1989, ISBN 0-20117928-8. [CT&P] Stephen K. Park and Keith W. Miller, "Random Number Generators: Good Ones are Hard to Find," _Communications of the ACM_, Vol. 31 #10, October, 1988, pp. 1192-1201 (also technical correspondence August, 1989, pp. 1020-1024, and July, 1993, pp. 108-110). P.J. Plauger, _The Standard C Library_, Prentice Hall, 1992, ISBN 0-13131509-9. Thomas Plum, _C Programming Guidelines_, Second Edition, Plum Hall, 1989, ISBN 0-911537-07-4. William H. Press, Saul A. Teukolsky, William T. Vetterling, and Brian P. Flannery, _Numerical Recipes in C_, Second Edition, Cambridge University Press, 1992, ISBN 0-521-43108-5. Dale Schumacher, Ed., _Software Solutions in C_, AP Professional, 1994, ISBN 0-12-632360-7. Robert Sedgewick, _Algorithms in C_, Addison-Wesley, 1990, ISBN 0-20151425-7. Charles Simonyi and Martin Heller, "The Hungarian Revolution," _Byte_, August, 1991, pp.131-138. David Straker, _C Style: Standards and Guidelines_, Prentice Hall, ISBN 0-13-116898-3. Steve Summit, _C Programming FAQs: Frequently Asked Questions_, AddisonWesley, 1995, ISBN 0-201-84519-9. [The book version of this FAQ list.]

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Sun Wu and Udi Manber, "AGREP -- A Fast Approximate Pattern-Matching Tool," USENIX Conference Proceedings, Winter, 1992, pp. 153-162. There is another bibliography in the revised Indian Hill style guide (see question 17.9). See also question 18.10.

Internet C Sites
Welcome to of the index of resources for numerical computation in C or C++. It is a collection of pointers to: - free source code available on the net, - articles and documents, especially those available over the net. This file is ftp://usc.edu/pub/C-numanal/numcomp-free-c.gz ftp://ftp.math.psu.edu/pub/FAQ/numcomp-free-c or c/numcomp-free-c on netlib (slightly outdated). Also see the last item on http://www.math.psu.edu/OtherMath.html The book reviews which were here have been deleted in order to combat bloat. You can find them in http://www.cmie.ernet.in/~ajayshah but be warned that we have a slow leased line and our systems are only up from 9 to 7 GMT+0530. Please see the section "interesting sites" below to get some help on how to retrieve software listed here. Table of Contents: * Explanations of fields * The index * f2c

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

* Other pointers * Interesting sites * Credits The index is biased towards fields I work in. Please send me suggestions, corrections and improvements. -Ajay Shah, ajayshah@cmie.ernet.in

Explanations of fields ---------------------Name if the archive has a obvious name, then that is shown. Otherwise I invent something sensible. Where is a pointer into a ftp site, or sufficient information to figure that out. The information at EOF may enlighten you if you are still stuck. Ideally I try to give information which is explicit enough for use with (say) ftpmail. Systems The default is Unix. If it runs on other systems this is shown, if it does NOT run on Unix this is shown. Language The default is ANSI C. The alternatives are K&R and C++. Author I try to give the name(s) and email addresses. Sometimes the email address is a contact person, even if it's not the author. Version This tries to identify a most-recent version and gives it's date. Description A one-line description Comments Are a few keywords thrown in to help you egrep. Many things are incomplete; tell me of anything which hurts your eyes. Please point me to goodies I've overlooked. If you have source code which may be of wide interest, please make it available to the net.

The index --------Name Where : AIPS++ library (beta) : ftp://aips2.cv.nrao.edu/pub/aips++/RELEASED/libaips-3

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Systems Language Author Version Description Comments

: : : : :

Unix C++ AIPS++ consortium, aips2-request@nrao.edu 3 A class library under development for radio astronomical calibration and imaging. : Released library has multidimensional array classes, FFT's gridding of ungridded data, containers, tables, a documentation extractor (from comments), etc.

Name Author Systems Version Description Where Comments

: : : : : :

ADOL-C Andreas Griewank et al. (griewank@mcs.anl.gov) Unix, cfront or g++ 1.5 (Dec 1993) Automatic differentiation package in C++ In pub/ADOLC at ftp sites info.mcs.anl.gov and nbtf02.math.tu-dresden.de : Contains LaTeX documentation. Associated with article in TOMS. See book "Automatic differentiation of algorithms" edited by George Corliss and Andreas Griewank, SIAM, Dec 1991, where the chapter by D. Juedes lists many other automatic differentiation packages.

Name Where Description Author Version

: : : : :

ajay in general on Statlib cholesky decomposition and drawing from MVN Ajay Shah, ajayshah@cmie.ernet.in 23 Sept 1991

Name Author Systems Version

: as274_fc.tar.z (42748 bytes) : Alan Miller (alan@dmsmelb.mel.dms.CSIRO.AU) Port to C and packaging by Ajay Shah (ajayshah@cmie.ernet.in) : Unix : 1 May 1993

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Description : High accuracy least squares routines with facilities for WLS for a subset of variables, changing the order of variables, dealing with singularities, calculating an estimated covariance matrix of the coefficients. Both fortran and C versions are presented, along with a regression testing setup using ten test programs. See article "Least Squares Routines to Supplement those of Gentleman" in Applied Statistics 41(2), 1992 by Alan Miller. Where : pub/C-numanal on usc.edu Comments : note the .z is the new gzip compression.

Name Where

: ASA : http://www.ingber.com/ ftp://ftp.ingber.com Description : adaptive simulated annealing: performing adaptive global optimization on multivariate nonlinear stochastic systems Language : either K&R or ANSI C Authors : Lester Ingber (ingber@alumni.caltech.edu) Comments : Is very actively developed. Version : 12.1, 10 Feb 1996

Name : AutoClass C Authors : Diane Cook & Joe Potts - U. Texas at Arlington Description : C implementation of AutoClass: an unsupervised Bayesian classification system that seeks a maximum posterior probability classification. Systems : SunSparc SunOS 4.1.3 Where : http://ic-www.arc.nasa.gov: /ic/projects/bayes-group/group/html/autoclass-c-program.html or send e-mail to taylor@ptolemy.arc.nasa.gov Language : ANSI C, GNU gcc version 2.6.3 Version : 1.0 Comments : source code provided Date : 26 April 95

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name Description Where Author Version

: : : : :

awesime a C++ task library explicitly designed for simulation. pub/cs/misc/Awesime on ftp.cs.colorado.edu Dirk Grunwald (grunwald@foobar.cs.colorado.edu) II

Name : bignum Where : pub/bignum on rpub.msu.edu ; ripem.msu.edu Description : directory filled with bignum software, and a file BIGNUMS.TXT which summaries bignum alternatives. Author : BIGNUMS.TXT is by Mark Riordan (mrr@scss3.cl.msu.edu) The ftp site is maintained by him. Version : April 1993.

Name Where Systems Description Author Version Comments

: : : : : : :

bignum.tar.Z in tars/math on einstein.mse.lehigh.edu (128.180.9.162) Unix Arbitrary Precision Integer Arithmetic Serpette, Vuillemin, Jean-Claude Herve 23 Sept 1990 Excellent. very fast. possible problems with unalloc call.

Name Where Author Description Version

: : : : :

blas.cpp.shar.z in pub/C-numanal on usc.edu Damian McGuckin (damianm@eram.esi.com.au) a BLAS in C++ beta, 8 May 1993

Name : c++ (5665 bytes) Author : U. Ruede (ruede@informatik.tu-muenchen.de) Description : Summary of 1992 workshop "Scientific Computing in C++" (plain text file) Where : mgnet/papers/Ruede on casper.cs.yale.edu

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Date

: August 4 1992

Name Where

: C++SIM : on arjuna.ncl.ac.uk pub/C++SIM/Source/C++SIM_PR1.0_tar.Z pub/C++SIM/Papers/C++SIM_EuropeA4.ps.Z pub/C++SIM/Papers/C++SIM_USLetter.ps.Z Description : SIMULA and SIMSET style simulation package in C++ with accompanying documentation. Authors : Mark Little (M.C.Little@newcastle.ac.uk) Daniel McCue (Daniel_McCue.WBST102A@xerox.com) Version : 1.0 (June 14th 1993) Comments : A complete simulation package for creating process based discrete event simulation as in SIMULA. The linked-list manipulation facilities provided by SIMSET are also provided in the package. The system is built in an objectoriented manner and the documentation provides information on how it can be modified and extended. Active objects in C++ can also be provided outside of the simulation package by simply inheriting the desired thread characteristic.

Name Where Systems Language Author Version Description Comments

: : : : : : : :

cdhc ftp://pasture.ecn.purdue.edu/pub/mccauley/grass/cdhc.tar.gz Unix C Darrell McCauley, mccauley@ecn.purdue.edu 1.0 (12 Sep 1994) A library for testing normality & exponentiality Draft docs at ftp://pasture.ecn.purdue.edu/pub/mccauley\ grass/tutorials/libcdhc-tutorial.ps.gz. Includes D'Agostino's D, Anderson-Darling, Cramer-Von Mises W^2, Kolmogorov-Smirnov, Chi-Square, Shapiro-Wilk, many others. Expands and fixes bugs in general/cdh in statlib.

Name

: cephes

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Author : Stephen L. Moshier, moshier@world.std.com Description : Emphasis on high accuracy special functions, but also contains useful code for matrices, eigenvalues, integration, ODEs, complex arithmetic, chebyshev approximation. Where : the many files in directory cephes on netlib Version : 2.2, June 1992

Name Where Systems

: Cfortran : zebra.desy.de [131.169.2.244] : VAX VMS or Ultrix, DECstation, Silicon Graphics, IBM RS/6000, Sun, CRAY, Apollo and HP9000. Language : C, FORTRAN Author : Burkhard Burow, burow@vxdesy.cern.ch, University of Toronto Version : 2.5 Description : A set of macros (cfortran.h = 1000 lines) allowing function calls to be made from C to FORTRAN and vice-versa. Comments : Good compact way of calling functions without translating. Easy to use.

Name Author Where Description

: : : :

Version

chernikov Ata Etemadi (atae@spva.physics.imperial.ac.uk) Volume 26, Issue 91 of comp.sources.unix computes the stochastic webs produced by the Chernikov equations (see Nature Vol. 326, April 1987) and produces a PGM image based on occupancy of cells. The equations essentially describe the path of a non-relativistic charged particle rotating about a magnetic field line, and experiencing a periodic electric field impulse. : v1.0, 3 April 1993

Name Where

: clapack : Start at http://www.netlib.org/clapack/index.html http://www.netlib.org/clapack/clapack.tar.z (10187795 bytes) Description : f2c translation of Lapack, with minor, mostly cosmetic improvements.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Author

Version Comments

: Jim Demmel (demmel@cs.berkeley.edu, http://http.cs.berkeley.edu/~demmel) Xiaoye Li (xiaoye@cs.berkeley.edu) Contact lapack@cs.utk.edu : Built off Lapack 2.0, 30 Sep 1994 : They have ported the Lapack testing and timing code also. Their clapack is known to pass all the tests.

Name Where Language Systems Description

: : : : :

Author

code++ in pub/code++ on elib.ZIB-Berlin.de C++ UNIX, GNU g++ and cfront C++ class library for ordinary differential equations and related problems. Contains lots of useful classes for linear algebra (vectors, matrices, linear solvers, pseudoinverses), and other utilities (minimal tool command language, etc.). The integration classes for ODEs are based on adaptive extrapolation methods (explicit Euler discretization for non-stiff, and implicit for stiff ODEs). Classes for continuous output, stepsize freezing, and variational equations are also provided, as well as an experimental multiple shooting environment for BVPs. : Andreas Hohmann, hohmann@sc.zib-berlin.de

Name Where Systems Language Description Author Version Comments

: : : : :

cvmath.cc (12263 bytes) in pub/C-numanal on usc.edu Unix C++ An include file to make complex math look like regular math. : Leonard Kamlet, lik@engin.umich.edu : 8 March 1993 : The file uses a lot of operator overloading, so that if x=a+ib and y=c+id, the code for multiplying the two together looks like z = x*y; Also, the file includes nrutil

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

from Numerical Recipes, and adds the complex versions for vectors and matrices.

Name Where Author Version Language Description Comments

: : : : : : :

CVODE netlib/ode/cvode.tar.Z Choen, Scott D. and Alan C. Hindmarsh 5 October 1994 Ansi C ODE solver Integrates ODE's. BDF or Adams-Moulton Formula. Implicit equation is solved with Functional or Newtontype iteration. Direct or iterative solution of the lin. eq. of the Newton iteration. Dense, diagonal, banded or sparse approximation of the Jacobimatrix of the right hand side of the ODE. Manual (91 p.) in postscript.

Name : dcdflib Authors : Barry W. Brown, James Lovato, Kathy Russell Description : Library of Routines for Cumulative Distribution Functions, Inverses, and Other Parameters Systems : Unix Where : odin.mda.uth.tmc.edu in pub/unix/dcdflib.c-1.0-tar.Z Language : K&R and ANSI C available. Version : 1.0, February 1994

Name Where Description Author

: : : :

dcg.shar in c on Netlib preconditioned conjugate gradient method Mark K. Seager, seager@lll-crg.llnl.gov

Name : dddd Where : in pub/dddd on madvax.uwa.edu.au Description : dynamical data determinism detector (works with time-series data). exploits Open windows 3.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Systems Version Author

: Unix : 21 Oct 1992 : Dave Watson, watson@maths.uwa.edu.au

Name Authors

: Diffpack : Hans Petter Langtangen (hpl@math.uio.no) Are Magnus Bruaset (Are.Magnus.Bruaset@si.sintef.no) + contributions from several other people Description : A development environment for object-oriented simulators based on PDEs. C++ source code and documentation. Systems : Tested on SGI/IRIX 5.2, C++ 3.2.1 HP/HP-UX 9.05, C++ 3.50 SPARC/Solaris 2.3, C++ 4.0 IBM/AIX 3.2.5, C++ 2.1.3.0 Relatively easy to port to other Unix platforms, does not work very well with g++. Where : netlib.att.com and mirror sites, directory diffpack Language : C++ (and a few C functions for GUI) Version : 1.0 Comments : See the Diffpack WWW Home Page on http://www.oslo.sintef.no/avd/33/3340/diffpack for presentation and the latest news. Date : April 28, 1995

Name Where Systems Description Author Version Comments

: : : : : : :

drpn ftp://ftp.alumni.caltech.edu/pub/dank/drpn.tar.Z Unix RPN calculator for digital signal processing Dan Kegel, JPL 1.1 A simple way to do add, multiply, FFT, sum, shift operators on a stream of fixed-length records of data. Handles several data types (16 bit int, 32 bit float). Used, for example, to process a synthetic aperture radar image.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name Where Systems Description

: : : :

dstool somewhere on macomb.tn.cornell.edu Unix, uses xview3 and open windows 3 Dynamical systems simulation package Plots Lorenz attractors and "other chaotic things" in realtime. Includes a expression evaluator.

Author Version

: : 1.1

Name : dtoa.c Where : in fp on Netlib Description : correctly rounded decimal <--> binary conversion

Name Version Author Description Where

: : : :

eigen.1.01.shar.Z (80545 bytes) 1.01, 25 March 1993 Nadav Har'El (nyh@gauss.technion.ac.il) Find the N largest eigenvalues and their eigenvectors of a real matrix ( < 700x700). Includes postscript documentation. : eigen directory on gauss.technion.ac.il (132.68.112.60)

Name Where Files Language Author Version Description

: : : : : : :

Comments

Euler By anonymous ftp from ftp.ku-eichstaett.de 212 kb /pub/unix/math/euler.tar.Z ANSI-C Rene Grothmann (rene.grothmann@ku-eichstaett.de) 3.18 Runs on UNIX/XWindow systems (OS/2 version available). Real and complex numbers and matrices. Lots of built in functions. Programming language. 2D/3D plots. ASCIIdocumentation and demo mode. Matlab like. : Tested on IBM Risc, Linux and Sun (with acc compiler)

Name

: fec

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Authors Description Where Language Version Date

: : : : : :

B. Bagheri (email?) A collection of finite element libraries in C++ pub/Math on karazm.math.uh.edu GNU C++ 1.1

Name Where Description Systems Version Author Comments

: : : :

FElt pub/felt on cs.ucsd.edu introductory finite element analysis Unix commandline or Unix + X HP-SUX, Sun, Linux, DOS. : 2.0, 28 February 1994 : Jason Gobat, jgobat@ucsd.edu Darren Atkinson, atkinson@ucsd.edu : postscript manual and mailing list exists.

Name Author Where Systems Language Version Description

: : : : : : :

Comments

femlib-1.1.tar.gz Michael Tiller (tiller@solace.me.uiuc.edu) pub/C-numanal on usc.edu UNIX C++ 1.1, June 17 1993 C++ class libraries for doing Finite Element simulations, Garbage Collection, Automatic Differentiation as well as a library for Sparse Matrices. : This release is still pretty rough but should compile with gcc-2.4.3, gnumake-3.6x, libg++-2.3.1 and makedepend (from X11 distribution).

Name : fft.shar Where : in c++ on Netlib Description : radix 2 FFT

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name Where Description Author Version Comments

: : : :

fft-sstuff.tar.z in pub/C-numanal on usc.edu summary about FFT code in C, including lots of source Peter J. McKinney (pm860605@longs.LANCE.ColoState.Edu) and Ron Mayer (mayer@acuson.com) : 19 March 1993 : Includes DDJ's improved version of Numerical Recipes four1().

Name Where Description Author

: : : :

fftsing ftp://wuarchive.wustl.edu/edu/math/software/msdos/modelling/ FFT of extremely long series; Singleton's mixed radix algo Javier Soley, FJSOLEY@UCRVM2.BITNET

Name Where Description Author

: : : :

frac in c on Netlib finds rational approximation to floating point value Robert Craig, AT&T Bell Labs - Naperville

Name Where Language Description

: : : :

fromskip send email to Skip Carter (address at EOF) C++ numerical derivatives with richardson extrapolation, runge-kutta code, monte-carlo integration, fredholm and voltera integral equation solvers, etc.

Name Where Systems Language Authors

FSQP, CFSQP send email to andre@eng.umd.edu many (including DOS) FORTRAN (FSQP), C (CFSQP) , Jian L. Zhou (jzhou@eng.umd.edu) and Andre L. Tits (andre@eng.umd.edu) (FSQP); Craig T. Lawrence (craigl@eng.umd.edu), Zhou and Tits (CFSQP). Version : FSQP: 3.3b, 9/93; CFSQP: 2.3, 11/8/95 Description : solution of constrained continuous optimization problems,

: : : : :

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Comments

possibly minimax (cost function is max of finitely many functions). CFSQP also includes efficient scheme to handle problems with many "sequentially related" objectives or constraints (e.g., finely discretized minimax problems or semi-infinite problems). : modified SQP scheme; successive iterates are all feasible (inequality constraints) or "semi-feasible" (equality constraints). 70 page manual. keywords nonlinear minimisation maximisation nonlinear programming

Name Author Where Description

: : : :

Systems Comments Version

fudgit_2.31.tar.Z (451691 bytes) Martin-D. Lacasse, isaac@physics.mcgill.ca pub/Fudgit on ftp.physics.mcgill.ca C-based fitting and data manipulation program (works on top of gnuplot). Gives you a C-like interpreted script language. : Unix only. : See entry on gnuplot elsewhere in this document. : 2.31, 13 April 1993

Name Where Description Author Version

: : : : :

gaut in general on Statlib upper-tail probabilities on normal and t densities Ajay Shah, ajayshah@cmie.ernet.in 12 May 1991

Name Where

: ga's : pub/galist/source-code/ga-source on ftp.aic.nrl.navy.mil (192.26.18.74) Description : many genetic algorithm optimisation libraries, all in C Comments : they are GAucsd 1.4 (Nici Schraudolph, nici@cs.ucsd.edu), GENEsYS 1.0 (Thomas Baeck, baeck@home.informatik.uni-dortmund.de) Genesis 5.0 (John J. Grefenstette, gref@aic.nrl.navy.mil), Goldberg's SGA in C (with a nCube version) by Rob Smith,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

rob@galab2.mh.ua.edu Also see survey of GA software in file GAsoft.txt at cs.ucsd.edu

Name Where Systems Language Author Version Description

: : : : : : :

GAlib http://lancet.mit.edu/ga/ UNIX, DOS/Windows, MacOS C++ Matthew Wall mbwall@mit.edu 2.3.2 (2.4 coming December 1995) Objects for doing genetic algorithm optimization

Name : gemmw Description : a highly portable Level 3 BLAS implementation of Winograd's variant of Strassen's matrix multiplication algorithm Where : in misc on Netlib Author : Craig C. Douglas, douglas-craig@CS.YALE.EDU Version : 22 May 1992

Name : genocop{,2}.tar.Z Where : in coe/evol on unccsun.uncc.edu (152.15.10.88) Description : nonlinear maximisation with linear constraints. You write C code for the function to optimise and link into genocop. Allowable ranges for each parameter can be defined. Author plans to do nonlinear constraints "soon". Author : ??, zbyszek@unccvax.ucc.edu Version : 2

Name Description Where Comments

: : : :

geometry archive containing many programs on geometry pub/contrib/comp_geom on geom.umn.edu Short summary as of 5 June 1993 geomview -- interactive geometry viewing for SGI IRIS evolver -- models evolution of surfaces driven by forces

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

hcad -- drawing hyperbolic polyhedra in 3d poincare disk (for X) invriemann -- inverse riemann mapping by circle packing riemannmap -- riemann mapping by circle packing kali - 2D euclidean symmetry pattern editor for SGI IRIS minneview -- general 3d viewing program for SGI IRIS polycut -- covering spaces of 3d euclidian space from inside crsolver -- conformal mapping, complex analytic functions (NeXT) automata -- automatic groups programs epsilon -- utility for squashing FP roundoff errors in data files hyper -- projective <--> conformal models of hyperbolic space omni_interp and interpolate -- interpolating between formatted data files kaleido -- constructing uniform polyhedra qhull -- general dimension convex hull computations program snappea -- hyperbolic structures computations vcs -- 3d voronoi diagram program viewwld -- viewing line drawings in 3d space (for Suns) vor2d -- 2d voronoi and delaunay diagrams, with cheyenne graphics

kaos -- interactive dynamical systems package (Suns) Name : gle Description : graphics layout editor script or menu driven program for composing a graphics page. Graphics primitives + PostScript file inclusion, plot generation from equations or tabular data + manipulation. Various output formats (X,ps,hpgl..) and utility programs (contour, surface, fits..) Systems : Unix, PC Where : wuarchive.wustl.edu:/graphics/graphics/packages/gle Version : 3.3b Language : ANSI C Author : Chris Pugmire, srghcxp@grv.grace.cri.nz

Name : gmp-1.3.tar.z Description : GNU multiple precision library

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Where Version Author

: in pub/gnu on prep.ai.mit.edu : 1.3, May 10 1993 : ?

Name Where Description Author Systems Comments Language

: : : : : : :

gmt kiawe.soest.hawaii.edu:/pub/gmt great scientific graphics ? Unix Fits the Unix philosophy. Postscript output supported. C

Name Where Systems Language Author Version Description Comments

: : : : : : : :

Gnans in ftp.mathematik.uni-Bremen.de:/pub/gnans Solaris 2.x, SunOS 4.1.x, SGI IRIX 5.x. C++ Bengt Martensson 1.3, 26 August 1994 Analyse deterministic and stochastic dynamic systems A program (and language) for dynamical systems. Includes simple scripting language. Graphical user interface. Copyleft. There is a mailing list.

Name Author Description Systems Where Version Comments Date

: : : : : : : :

gnufit10.tar.gz Carsten Grammes (cagr@rz.uni-sb.de) Gnuplot 3.2 with nonlinear regression features added Most Unix, OS/2 2.x. Needs popen(3). pub/utils in coli.uni-sb.de 1.0 Levenberg-Marquadt nonlinear least squares 28 June 1993

Name Authors

: gnuplot3.5.tar.Z : coordinated by Alex Woo (woo@playfair.stanford.edu)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Description Systems Where Version Comments

: : : : :

Date

plotting package for functions and data all systems, all graphics file formats, all output devices in pub/gnuplot on ftp.dartmouth.edu 3.5 Includes probability functions, 3d plotting with contours and hidden line removal, parametric functions. Has manual, online help, commandline editing and a newsgroup comp.graphics.gnuplot Can be used as a C library. : 17 August 1993

Name : go.c.Z (7288 bytes) Where : in pub/C-numanal on usc.edu Description : Calculate gaussian quadrature rules. Translation of Netlib: go/gausq.f using f2c with some hand-cleaning. need a log gamma function. Comments : numerical integration

You

Name Where Author Description

: : : :

Version Comments

hare (Hazard Regression) file hare (a shar file) in S directory on statlib Charles Kooperberg (clk@stat.washington.edu) estimates the conditional hazard rate based on possibly censored data and covariates. Includes parametric and non-parametric, additive and non-additive proportional and non-proportional hazards model as special cases. Addition and deletion of basis functions make the fit highly adaptive. : statlib, last update April 21, 1993 : actually the objective of this file is to give a end-user of the S statistical package this functionality. But the actual computation is done in C. Described in Univ. of California, Berkeley, Stat tech rep 389. Available from the author.

Name Where

: heft (Hazard Estimation with Flexible Tails) : file heft (a shar file) in S directory on statlib

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Author : Charles Kooperberg (clk@stat.washington.edu) Description : estimates the unconditional hazard rate using splines. Knot addition, deletion and two extra tail terms make the fit highly adaptive. Version : statlib, last update April 21, 1993 Comments : actually the objective of this file is to give a end-user of the S statistical package this functionality. But the actual computation is done in C. Described in Univ. of California, Berkeley, Stat tech rep 388. Available from the author.

Name Authors Description Where Language Date

: : : : : :

hepC++.html Marcus Speh (?) Information on C++ applications in HEP in pub/www/projects on info.desy.de access through WWW June 21 1993

Name : HL_Vector.shar Authors : oleg@ponder.csci.unt.edu, oleg@unt.edu Description : Aitken-Lagrange interpolation over the table of uniform or arbitrary mesh, and the Hook-Jeevse multidimensional minimizer. Systems : Unix Where : netlib (ftp://netlib.att.com/netlib/c++/hl_vector.shar.Z) Language : C++ (gcc 2.5.8) Version : 1.0 Comments : Test drivers and test run outputs are included, too. Commented. Needs LinAlg.shar Date : May 27, 1992

Name Authors Description Where Language

: : : : :

hooke.c Mark Johnson Hooke and Jeeves Algorithm netlib/opt/hooke.c C

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name Where Systems

: : : : : Language : : Author : Version : Description : Comments :

IR-STAT-PAK ftp://potomac.ncsl.nist.gov/pub/irstat/irstat.tar.gz Written for Solaris but it has been compiled under Linux and SunOS. An AIX version required a few changes but not many. The documentation discusses the O/S specific code. ANSI C except that there are three arguments to main(). This is unnecessary and will be removed in the next release. J. Blustein 1.02 (released 30 August 1995) Descriptive and analytic statistics for the TREC IR trials information retrieval recall precision Tukey

Name Where Author Description Version

: : : :

ieeetest.zoo (65783 bytes) in pub/C-numanal on usc.edu Stephen L. Moshier, moshier@world.std.com includes a improved version of paranoia, and code for testing the precision of the C I/O library on FP I/O. : 8 March 1993

Name Where Systems Description

: : : :

Author Version

IND Tree Package available in the US only, contact author Unix Tree classification routines (supervised learning) including reimplementations of parts of CART, C4.5, and Bayesian and MDL methods with tree smoothing and "decision graphs". The package is made up of a collection of interconnected Unix tools. It comes with a lot of documentation. : Wray Buntine, wray@kronos.arc.nasa.gov : Version 2.1, January 1993

Name Where

: in-spice : part of Spice. less-buggy.

SPICE3E1 is free, SPICE3E2 is not-free

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Description : files src/lib/ni/ni{integ,comcof}.c are first- (backward euler) and second- (trapezoidal) order integrator and a >6 order GEAR.

Name : jgraph.Z Author : Jim Plank (jsp@princeton.edu) Description : filter for producing {encapsulated,} postscript using input in a script language. Presentation quality results. Systems : Unix Where : in pub on princeton.edu, also jgraph.shar in misc on netlib Language : C Version : 8.3 Comments : Very useful for post-processing the results of a computational program. E.g. an awk program can turn numbers into jgraph code, or a C program can generate jgraph directly. The script language gives a very high degree of control over the final appearance. There is a mailing list. Date : Nov 30 1992

Name Where Author Description Language Version

: : : : : :

kalman.tar.gz (22747 bytes) in pub/C-numanal on usc.edu Skip Carter (skip@taygeta.oc.nps.navy.mil) A class library for Kalman filtering C++ (works with g++ 2.4.2 also) v1.0, 3 July 1993

Name : Karma Where : graphics/graphics/packages/karma on wuarchive.wustl.edu Description : DSP package

Name : Kaskade Description : Linear elliptic FEM solver written in C. Reads problem description from plain text file - can be (mis)used as triangular mesh generator. Graphical output under X11 and MacOS.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Authors

Systems Where

Mailing list. : 2-D -- Rainer Roitzsch (roitzsch@sc.zib-berlin.de) 3-D -- Bodo Erdmann (erdmann@sc.zib-berlin.de) Konrad-Zuse-Zentrum fuer Informationstechnik (ZIB) : compiles on Unix and Macintosh : elib.zib-berlin.de:/pub/kaskade. (The slightly outdated user manual is in pub/kaskade/AltesZeug/tr-89-4.ps - in english)

-Ajay Shah, (213)749-8133, ajayshah@rcf.usc.edu Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!spool.mu.edu!howland.reston.ans.net!usc!usc!not-formail From: ajayshah@cmie.ernet.in Newsgroups: comp.lang.c,comp.lang.c++,sci.math.num-analysis,sci.comp-aided,sci.op-research Subject: Part 2 of 3: Free C,C++ for numerical computation Followup-To: sci.math.num-analysis Date: 6 Mar 1996 05:24:13 -0800 Organization: Centre for Monitoring Indian Economy, Bombay, India Lines: 802 Sender: ajayshah@almaak.usc.edu Distribution: world Message-ID: <4hk3lt$3i6@almaak.usc.edu> Reply-To: ajayshah@cmie.ernet.in NNTP-Posting-Host: almaak.usc.edu Keywords: source code, numerical statistical scientific computation Xref: senator-bedfellow.mit.edu comp.lang.c:177098 comp.lang.c++:176366 sci.math.num-analysis:26774 sci.comp-aided:1258 sci.op-research:5408

Name Where Systems Language Author Version Description Comments

: : : : : : : :

Kinetic Compiler and Integrator (kci) ftp://mac-dev.ruc.dk/pub/kneth/kc.tar.Z Unix and MS-DOS ANSI-C and the tools lex and yacc Kenneth Geisshirt (kneth@fatou.ruc.dk) and Keld Nielsen 1.05 Chemical reaction simulator and ODE solver The kci package is able to simulate a set of chemical

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

reactions and/or solve ODEs. The package also comes with many numerical libraries e.g. matrices (very small lib.), ODE solvers, integration of real functions, and find eigenvalues/vectors of general matrices. There is also a small library for symbolically manipulating expressions.

Name Authors Description Where Language Version Comments

: : : : : : :

Lapack++ J. Dongarra, R. Pozo, D. Walker C++ version of some of lapack fortran code. ftp from netlib2.cs.utk.edu in lapack++/* C++ 0.9 beta C++ version of some of lapack fortran code. Developmental version of proposed C++ version of lapack. Contains blas.h++ etc, but needs Fortran library to link. Has overview paper (9 pages ps), release notes (7 page ps)

Date

Name Where Systems Description Author Comments

: : : : : :

LASSPTools /pub/LASSPTools at lassp-ftp.msc.cornell.edu Unix Data manipulation and entry tools for Unix. Various people in the Cornell physics department A diverse set of tools by various people at the Laboratory of Atomic and Solid State Physics at Cornell. Most useful for a set of X-windows applications and UNIX filters for interactive data manipulation. For instance, there's a mouse-operated track-ball that outputs a rotation matrix describing the orientation of the ball.

Name Description Version Where

: : : :

leda library of efficient data types and algorithms v3.3, Jan 1996 http://www.mpi-sb.mpg.de/LEDA/leda.html ftp.mpi-sb.mpg.de in pub/LEDA

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Author Comments

email leda@mpi-sb.mpg.de : Christian Uhrig : includes code on computational geometry There is a mailing list on it; contact listserv@dworkin.wustl.edu

Name Authors Description Systems Where Language Version Comments

: : : : : : : :

Date

LinAlg.shar oleg@ponder.csci.unt.edu, oleg@unt.edu Basic Linear algebra in C++ Unix/Mac netlib (ftp://netlib.att.com/netlib/c++/lin_alg.shar.Z) or ftp://replicant.csci.unt.edu/pub/oleg/LinAlg.shar C++ 3.1 Contains declarations of the Matrix, Vector, subMatrix over the real domain, and *efficient* and fool-proof implementations of level 1 & 2 BLAS (element-wise operations + various multiplications), transpositions and determinant evaluation/inversion. There are operations on a single row/col/diagonal of a matrix. The "new style" of returning matrices (via LazyMatrix) and filling them out. See LinAlg.h for the complete list of classes and functions, and vmatrix.cc, vvector.cc test drivers as to how the features can be used. See README for hints. The code made ANSI-C++ compliant and very portable (compiles with gcc v2.6.3). Feb 7, 1995

Name Where Author Description

: : : :

Version Comments

logspline file logspline (a shar file) in S directory on statlib Charles Kooperberg (clk@stat.washington.edu) logspline density estimation fully automatic nonparametric density estimation adaptive smoothing using splines : statlib, last update April 21, 1993 : actually the objective of this file is to give a end-user

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

of the S statistical package this functionality. But the actual computation is done in C. Described in Journal of Computational and Graphical Statistics, (1993), vol 1, 301-328.

Name Where Description Author Version Comments

: : : : : :

lpsolve volume02 of comp.sources.reviewed very good mixed integer linear program solver Michel Berkelaar (michel@es.ele.tue.nl) 1.4, 18 January 1994 Its core is a sparse matrix dual simplex LP solver. MILP problems are solved with a branch-and-bound iteration over LP solutions. It uses a lex+yacc parser to read a human-friendly algebraic input format. The author has used the program to solve LP problems up to about 30000 variables and 50000 constraints (on a 22 MFLOPS HP9000/750).

Name Author Systems Version Description

: : : : :

Language Where

lsqrft15.zip Michael Courtney (michael@amo.mit.edu) OS/2 2.x, UNIX 1.5, 28 February 1994 Non-linear least squares fitting program that opens a pipe to gnuplot and plots data and attempted fit. It's easy to define your own functions and recompile. Can fit multidimensional data to functions of more than one independent variable. You can choose whether to vary parameters. : ANSI C : pub/os2/2_x/unix/lsqrft*zip on ftp.cdrom.com

Name Where Description Author Version

: : : : :

machar in misc on Netlib find out properties of floating point hardware William J. Cody, cody@antares.mcs.anl.gov, and Tim Hopkins October 1985

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name : madpack Where : Netlib, in pdes/madpack Description : MADPACK is a a compact package for solving systems of linear equations using multigrid or aggregation disaggregation methods. Imbedded in the algorithms are implementations for sparse Gaussian elimination and symmetric Gauss-Seidel (unaccelerated or accelerated by conjugate gradients or Orthomin(1)). This package is particularly useful for solving problems which arise from discretizing partial differential equations, regardless of whether finite differences, finite elements, or finite volumes are used. Author : Craig Douglas, douglas-craig@cs.yale.edu Comments : see directory mgnet on casper.cs.yale.edu too

Name Where Systems Language Authors Description

: : : : : :

Comments

marsaglia-random archimedes.nosc.mil:pub/ada/random/* highly portable C, Pascal, Ada G Marsaglia, M G Harmon & T P Baker, V Broman. highly machine-independent uniform RNG, requires 24-bit fixed point or floating point arithmetic. 953118087 different seed pairs give pseudo-random sequences with period about 2**144. passes stringent randomness tests. : correct operation with 24-bit floats seems to require a guard bit. failing that, try fixed point arithmetic.

Name Author Version Systems Description

: : : : :

matcalc M. Gerberg, E.J. Moore, University of New South Wales, Australia 2.1 Unix, VMS and DOS installation scripts exist Matlab-like numerical solver. Good support of singular problems. Well structured - easy extension with own C routines

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Where

which can use the matcalc library. : netlib/matcalc on draci.cs.uow.edu.au

Name Author Where

: matclass_info : Keith Briggs (Keith.Briggs@physics.uwa.edu.au). : Posted on sci.math.num-analysis and comp.lang.c++ Also see http://www.pd.uwa.edu.au/Keith/homepage.html Description : A comprehensive catalog of C++ matrix classes. I am not a C++ junkie (yet); it has a lot of information not present here. Version : Last posted 6 April 1994.

Name Description Author Systems Where Comments

: : : : : :

Matclass a C++ class for numerical computation Chris Birchenhall (chris.birchenhall@mailhost.mcc.ac.uk} Unix and PC ftp from ftp.mcc.ac.uk pub/matclass/pc and pub/matclass/unix Offers a general purpose dense, real matrix class Has a family of decomposition classes based on LU, Cholesky, Householder QR and SVD Has a family of OLS regression classes based on above decompositons A family of special function classes Random number class Has a simplified I/O structure Very good tex manual.

Date Version

: :

Name Authors Description Systems Where

: : : : :

matcom yak@techunix.technion.ac.il (Keren Yaron) Matlab --> C++ translator SunOS (324k), MSW (1.1M) http://techunix.technion.ac.il/~yak/matcom.html http://rio.esm.vt.edu/mirror/matcom

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(?) ftp://ftp.funet.fi/pub/sci/math/matlab (?) ftp://ftp.eeng.dcu.ie/pub/matlab/MATCOM Language Version Comments Date : : beta2 : : 10 Feb 1996

Name Where Author Description

: : : :

Version

matmult.tar.z in pub/C-numanal on usc.edu Clark Thomborson Several C-language codes for n * n matrix multiply, n a power of 2, developed as a laboratory exercise in the Spring of 1993 for MIT course 6.891, "Source Code Optimization for Workstations and Supercomputers." The sources are commented, however the recursive SRM (shuffled-row major) algorithm is obscure. Offered "as is" into the public domain by the course instructor. : 7 May 1993

Name Where Description Author Version

: : : : :

matrices.asc inside ddj9106.zip in published/dr-dobbs on ftp.uu.net efficiently raise matrices to an integer power Victor Duvanenko June 1991

Name : matrix-multiply.shar.z Where : in pub/C-numanal on usc.edu Description : collection of net postings and email about fast matrix multiply Includes C source. Version : 1 May 1993, updated 4 June 1993 Comments : also see matmult.tar.z in this file.

Name Where

: matrix.tar.Z : in ftp-raimund/pub/src/Math on nestroy.wu-wien.ac.at

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(137.208.3.4) Author : Paul Schmidt, TI Description : Small matrix library, including SOR, WLS

Name Where Version Description

: : : :

matrix041.zip in mirrors/msdos/c on wuarchive.wustl.edu 0.41, Sept 23 1993 Small matrix toolbox

Name : Matrix.tar.Z Where : in pub ftp.cs.ucla.edu Description : The C++ Matrix class, including a matrix implementation of the backward error propagation (backprop) algorithm for training multi-layer, feed-forward artificial neural networks Version : 10 July 1993 Systems : Can use either g++ or cfront. SunOS, Solaris 2, NeXT, SGI, Linux. Author : E. Robert (Bob) Tisdale, edwin@cs.ucla.edu

Name : mclaughl.lst Where : inside ddj8909.arc in published/dr-dobbs on ftp.uu.net Description : source code (500 lines) associated with article on Simulated Annealing by Michael P. McLaughlin. Version : September 1989

Name Where

: meschach : in c/meschach on netlib pub/meschach on thrain.anu.edu.au Systems : Unix, PC Description : a library for matrix computation; matrix, vector, permutation, sparse matrix data structures; basic linear algebra; min/max, sorting & componentwise operations; dense LU, Cholesky, QR, LDL factorisations; dense eigenvalues/vectors, singular value decomposition; sparse

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Author Version

matrix factorisations (LU, Cholesky, BKP); iterative methods; error handling; input/output : David E. Stewart, des@thrain.anu.edu.au : 1.2a, 28 February 1994

Name Where Systems Description Author Version

: : : :

meschach in c/meschach on netlib Unix, PC a library for matrix computation; more functionality than Linpack; nonstandard matrices : David E. Stewart, des@thrain.anu.edu.au : 1.1, 8 April 1993

Name Where Systems Language Author

mfloat in math on simtel. DOS written C++ and 80x86 assembly, useful for C, C++, Pascal Kaufmann Friedrich, fkauf@fstgds06.tu-graz.ac.at Mueller Walter, walter@piassun1.joanneum.ac.at Version : 2.0 into beta testing 2 June 1994. Description : fast high precision FP arithmetic (upto 77 digits) Comments : Shareware ($25).

: : : : :

Name Authors Description Where Language Date

: : : : : :

MG-mglib.html Marcus Speh Information on development of a C++ library for multigrid in pub/www/projects on info.desy.de access through WWW June 21 1993

Name : MIDAS Authors : European Southern Observatory Description : Tools for image processing and data reduction, with an accent on applications in astronomy.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Systems Where Language Version Comments Date

: : : : :

all major Unix, Linux, VMS ftphost.hq.eso.org:midaspub/linux for example ANSI C and Fortran f77. 94MAYpl2 Binaries are freely available, source is free to nonprofit research institutions. A contact person is resy@eso.org : 19 October 1994

Name Where Systems Description Author Version Comments

: : : : : : :

minit volume 7 of comp.sources.misc Unix linear programming by dual simplex method Badri Lokanathan 1.0, July 1989 don't miss minit.p1

Name Author Description Where Comments Date

: : : : : :

mm.c and mmgen.c Mark Smotherman (mark@cs.clemson.edu) benchmarking matrix multiply in pub/programs/mark on ftp.cs.clemson.edu includes a lot of code for fast matrix multiply 24 June 1993

Name : morrow.arc and gamaze.asc Where : inside ddj9104.zip in published/dr-dobbs on ftp.uu.net Description : genetic algorithm for optimisation, associated with article on the subject by Mike Morrow. Version : April 1991

Name Where Systems Language Author

: : : : :

Mrandom (version 1) Comp.sources.unix, Volume 25, Issue 23, December 1991 4.3bsd Unix C Clark Thomborson

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Version : 1, 12/91 Description : bug fix for 4.3bsd Unix random() Comments : random number generator, 4.3bsd Unix library routine

Name Where

: Mrandom (version 2.3) : anon ftp from theory.lcs.mit.edu, directory pub/cthombor, have submitted to comp.sources.unix Systems : 4.3bsd Unix Language : C Author : Clark Thomborson Version : 2.3, 8/92 Description : bug fix for 4.3bsd Unix random(), interface to other RNGs Comments : random number generator, 4.3bsd Unix library routine

Name Author Systems Version Description Where Comments Review

: : : : : : : : : : :

MXYZPTLK (mxyzptlk.tar.Z) Leo Michelotti (michelot@calvin.fnal.gov) Unix, CC++, g++ (has been ported to others) 3.1 (Sep, 1994) Automatic differentiation and differential algebra package in C++ ftp calvin.fnal.gov (in directory pub/outgoing/michelotti/MXYZPTLK Contains old 1990 PostScript documentation. Some demo programs demonstrate features not documented. Complements ADOL-C. Features complex mode. Easier to use, but possibly not as efficient for large problems. (Keith Briggs (Keith.Briggs@physics.uwa.edu.au)

Name Where

: newmat : volume47, issue 38-47 of comp.sources.misc SIMTEL msdos/cpluspls/newmat08.zip ftp://tahi.isor.vuw.ac.nz/pub/newmat08/newmat08.tar.gz Language : C++ Systems : Unix (g++, AT&T), MS-DOS (Borland, Watcom, MS) Description : a very thorough matrix class

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Author Version

: Robert Davies (robert.davies@vuw.ac.nz) : v8, 19 Jan 1995

Name Where

: nlmdl : in pub/arg/nlmdl at ccvr1.cc.ncsu.edu (128.109.212.20) in volume 16 of comp.sources.misc Language : C++ Systems : Unix, MS-DOS (Turbo C++) Description : a library for estimation of nonlinear models Author : A. Ronald Gallant, arg@ccvr1.cc.ncsu.edu Comments : nonlinear maximisation, estimation, includes a real matrix class Version : January 1991

Name Where Language Description Author

: : : : :

nonlinear in pub/inls-ucsd on inls.ucsd.edu various archive of programs in nonlinear dynamics, signal processing various, contact person is mbk@lyapunov.ucsd.edu (Matt Kennel)

Name Authors Description Systems Where Language Version Comments

: : : : : : : :

Date

plplot4p99i.zip or plplot4p99i.tar.gz Maurice LeBrun and Geoff Furnish scientific plotting package and Tk plotting widget Unix, VMS, MSDOS, Amiga. Wide variety of output drivers. dino.ph.utexas.edu in /plplot Fortran, C, C++, Tcl 4.99i (beta) Wide range of plot types including line (linear, log), contour, 3D, fill, etc. Approx 1000 characters (including Greek and mathematical) in extended font set (Hershey). Strong X-windows support, with Tk plotting widget that supports zoom, pan, dump to file or printer, page layout, etc. Distributed rendering supported. : 6 Sep 1994

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name Where Description Systems Comments

: : : : :

Project Northstar northstarftp.dartmouth.edu (129.170.24.135). courseware supporting mathematics and engineering classes Unix, known to work on IBM,HP,Sun,DEC,Convex. Not free, but freely available for .edu use.

Name : QMG Author : S. Vavasis, Cornell, vavasis@parc.xerox.com Description : Unstructured finite element mesh generation for 3D polyhedral objects with complicated geometry Systems : Sun/SunOS 4.1, Sun/Solaris, IBM RS6000/AIX, HP9000s800/HP-UX Where : http://www.cs.cornell.edu/Info/People/vavasis/qmg-home.html Language : C++ Version : 1.0 Date : 9 May 95

Name : nrutil Where : ftp://swarm.wustl.edu/pub/nrutil/nrutil.tar.gz Description : Appendix B of Numerical Recipes 2nd ed, a group of vector/matrix initialisation function which NR has standardised on. Author : Numerical Recipes is by William Press et al. This package is maintained by James C. Hu, jxh@cs.wustl.edu. Version : 1 August 1994 Comments : Note this is public domain, while none of the other NR source is.

Name Where Author Description

: : : :

nurbs.tar.Z in /pub/misc/unix/nurbs/nurbs.tar.Z on unix.hensa.ac.uk W. T. Hewitt et.al. Data structures and procedures for creation and manipulation of B-Spline curves and surfaces.

Name

: ObjectProDSP

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Authors

: Mountain Math Software Contact Paul Budnik, support@mtnmath.com P. O. Box 2124, Saratoga, CA 95070 (408) 353-3989 Description : Tool for DSP and object framework for interactive science and engineering applications. Systems : Linux binaries available, you can build on any Unix+X. Where : pub/linux/packages/dsp on tsx-11.mit.edu pub/Linux/devel/opd on sunsite.unc.edu Language : C++ Version : Beta 0.1, but likely to be more stable than your usual beta 0.1 product. Comments : Released under GPL. Copious documentation. Date : 1 October 1994.

Name Where

: Octave : ftp.che.utexas.edu:/pub/octave/octave-M.N.tar.gz. Binaries for some systems are also available. Systems : Compiles and runs on SPARC, RS/6000, DEC/Ultrix, i386/Linux, and probably most Unix systems that have a working port of g++ and libg++. A port to OS/2 and DOS is mostly working but not quite ready for release yet. Language : C/C++/Fortran Author : John W. Eaton Version : 1.1, Mon Jan 23 10:16:43 GMT+0530 1995 Description : Matlab-like interactive system for numerical computations Comments : Includes C++ classes for matrix manipulation, numerical integration, and the solution of systems of nonlinear equations, ODEs and DAEs. Distributed under the GPL. 230 page texinfo manual. 2d and 3d plotting using gnuplot.

Name Where Systems Description Author

: : : : :

ols ftp.uu.net in usenet/comp.sources.reviewed/volume01/ols almost anything, but it's most useful under Unix A small linear regression package dressed as a Unix tool Ajay Shah, ajayshah@cmie.ernet.in

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Version

: v1.00, late 1991

Name Where

: opbdp : ftp://ftp.mpi-sb.mpg.de/pub/guide/staff/barth/opbdp/ http://www.mpi-sb.mpg.de/~barth Systems : Unix Language : C++ (needs a compiler that supports templates) Author : Peter Barth (barth@mpi-sb.mpg.de) Version : 1.0 #0 (29.5.95) Description : An implicit enumeration algorithm for solving linear 0-1 optimization problems. A bunch of heuristics for selecting a branching literal. Several preprocessing techniques (coefficient reduction, fixing, equation detection). Preprocessed problem can written to a file readable for CPLEX and lp_solve. Comments : Technical report included. If your favorite linear-programming based solver fails on your problem you might give opbdp a chance.

Name Where

: : : Author : Language : Systems : Version : Description : Comments :

p-wavelets.tar.Z ftp://pandemonium.physics.missouri.edu/pub/wavelets http://theory.physics.missouri.edu Eric L. Veum (veum@pandemonium.physics.missouri.edu) ANSI C Unix, with X-windows March, 1995 Compactly Supported Wavelets Transform/Inverse Transform Transform and inverse transform for compactly supported wavelets with variable scaling factors, of which the special case of 2 are the Daubechies wavelets. Generates phase space time-frequency 3-D graphics if desired.

Name : pdes (sortof) Where : pub/pdetools at info.mcs.anl.gov Description : extensive collection of C for linear and nonlinear systems, derived principally from pdes.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name : p4.tar.Z Where : pub/p4 on info.mcs.anl.gov Description : a library for writing parallel programs for shared-memory or message-passing. It will work on a network of workstations or on parallel hardware. Author : lusk@mcs.anl.gov Version : July 28, 1992

Name Where

: : : Systems : Language : Author : Version : Description : Comments :

Para++ ftp.loria.fr/pub/loria/numath/para++ http://www.loria.fr/~coulaud/parapp.html Unix C++,PVM or MPI O. Coulaud (Olivier.Coulaud@loria.fr), E. Dillon 0.9 C++ Bindings for Message Passing Libraries. The aim of Para++ is to provide C++ bindings to use a message passing library (currently PVM or MPI), without the user had to worry about PVM or MPI. Para++ is based on the SPMD parallel programming method.

Name Where Systems Description Comments

: : : : :

paranoia research.att.com in dist; check netlib/paranoia too Unix exercise the edges of your floating point implementation also see `ieeetest' in this file.

Name Where

: Pari/GP : ftp://megrez.math.u-bordeaux.fr/pub/pari/pari-1.39a.tar.gz Also at math.ucla.edu Mailing lists exist. Contact pari-users-request@math.uic.edu or pari-implementors-request@math.uic.edu Description : PARI/GP is a package which is aimed at efficient

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Systems

Version Author

computations in number theory, but also contains a large number of functions unrelated to number theory. It is somewhat related to a Computer Algebra System, but is not really one since it treats symbolic expressions as mathematical entities such as polynomials, series, matrices, etc..., and not as expressions per se. However it is often much faster than other CAS, and contains a huge number of specific functions not found elsewhere, essentially for use in number theory. In particular, and especially so in the present release, there is a very large package for working in general algebraic number fields. : Binaries available for SPARC v7, v8, DEC Alpha, HP-PA. In the future, Mac (68k and powerPC). Intel hardware may have unsupported versions. : 1.39a, 19 January 1995 : pari@math.u-bordeaux.fr

Name : pca Where : in multi on Statlib Description : principal component analysis

Name Where Description Author

: : : :

perlman.Z in a on Netlib normal, chi-squared and F distributions Gary Perlman

Name Where Language Systems Description

: : : : :

piecewise.tar.Z (68025 bytes) pub/math on monster.resmel.bhp.com.au (134.18.3.1) C Unix (DOS if getopt available) Piecewise finds a piecewise linear approximation to a 1D function. The program provides two methods to find the approximating segments, both satisfying an L infinity error norm and both SUB-OPTIMAL. The user specifies the

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Author

Version Comments

tabulated function values and an error bound and the program returns the endpoints of the line segments that approximate the function. The operation is fast (essentially a single pass through the data) and works reasonably well on data with low noise. If the noise level is too high an alternative approach using smoothing splines should be used. : Original algorithms by Ivan Tomek and F. Gritzali & G.Papakonstantinou Port to C and packaging by Tim Monks (tim@resmel.bhp.com.au) : 3 March 1991 : keywords linear splines

Name Where Author Description Comments

: : : :

pierreQP.tar.Z (17680 bytes) in pub/C-numanal on usc.edu Pierre Asselin, pa@verano.sba.ca.us Extremely good package for calculation of gaussian quadrature rules : numerical integration

Name : polyfit.tar.Z Description : fit polynomials to data Where : in ftp-raimund/pub/src/Math on nestroy.wu-wien.ac.at (137.208.3.4) Author : Ted Stefanik, ted@adelie.Adelie.COM Version : 8 August 1989

Name Where Description Version

: : : :

praxis in math on Simtel derivative-free maximisation July 1987

Name Where Language

: presto : pub/presto1.0.tar.Z on cs.washington.edu : C++

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Systems : Unix-like OS on (moderate) multiprocessor machines Description : C++ routines for fine-grained parallel programming (lightweight threads) on multiprocessors. Tuned for the Sequent machines, but highly adaptable and customizable. Author : Brian N. Bershad, Edward D. Lazowska, Henry M. Levy Version : Version 1.0 is an optimized version by John E. Faust. (All above are from U. Washington, Seattle) Comments : Presto was the subject of a number of research papers in multiprocessor OS. Version 1.0 looks usable (ie not experimental anymore).

Name Authors Description Where Language Comments

: : : : : :

proj-4.?.tar.Z Gerald I. Evenden (gie@charon.er.usgs.gov) Unix tool for cartographic projection and unprojection in pub on charon.er.usgs.gov ANSI and POSIX C has beautiful (TeX) manual in postscript form

Name : psuedo.asc Where : inside ddj9105.zip in published/dr-dobbs on ftp.uu.net Description : implements R250 random number generator, from S. Kirkpatrick and E. Stoll, Journal of Computational Physics, 40, p. 517 (1981). Author : W. L. Maier

Name : Radix-2 FFT Authors : oleg@ponder.csci.unt.edu, oleg@unt.edu Description : Radix-2 DFT of a real or complex sequence, or sin/cos/complex Fourier integral of an evenly tabulated function. Systems : Unix/Mac Where : netlib (ftp://netlib.att.com/netlib/c++/fft.shar.Z) Language : C++ (gcc 2.5.8) Version : 1.0 Comments : The input can be either real or complex with/without zero padding, the full complex transform or only

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Date

real/im/abs_value part of it can be obtained. Test drivers and test run outputs are included, too. Commented. Needs LinAlg.shar : May 27, 1992

Name : random Where : bsd-sources/src/lib/libc/gen on gatekeeper.dec.com Description : the BSD C library random number generator

Name : random-c Where : in c on Simtel Description : portable, good random number generator

Name : range.tar.Z (206015 bytes) Where : in pub on ftp.math.tamu.edu Description : C++ class for interval arithmetic. Associated with article in TOMS, Dec 1992 title "Precise computation using range arithmetic, via C++" Author : Oliver Aberth and Mark J. Schaefer Version : October 1994

Name Where

: ranpm : in prog/libraries on ftp.inria.fr (128.93.1.26) also in volume5 of comp.sources.misc in "random" Description : the Park-Miller "minimal standard" random-number generator Author : Ajay Shah, ajayshah@cmie.ernet.in Version : February 1992 Comments : there are several other independent implementations, all are quite alike

Name : ranlib-c Where : pub/unix/ranlib.c-1.1-tar.Z on odin.mda.uth.tmc.edu Description : large library for random variate generation from many

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Author Version

univariate and multivariate distributions : Barry Brown, bwb@odin.mda.uth.tmc.edu : v1.1, 24 Mar 1994

Name : rktec.c.Z (20870 bytes) Where : in misc on netlib, or pub/papers/Hosea on math.niu.edu Description : computing truncation error coefficients of Albrecht's error expansion for Runge-Kutta formulas. Version 2.1 adds a radial stability region "plotter". Author : Mike Hosea (mhosea@math.niu.edu) Version : v2.1, 5 June 1994 Comments : The niu site also has some techreports.

Name Where

: rlab : ftp://evans.ee.adfa.oz.au/pub/RLaB also ftp://csi.jpl.nasa.gov/pub/matlab/RLaB Files 702 kb rlab-1.19a.tar.gz 384 kb rlap-2.0.tar.gz 74 kb rblas-1.1.tar.gz 30 kb rfft-1.2.tar.gz 31 kb rnlib-1.1.tar.gz Systems : Compiles and runs on Sun4, RS/6000, DEC/Ultrix, SysV/R4 i386, Linux, HP-UX, SGI. Broadly, should work on any Unix. Language : C + Fortran Author : Ian Searle (ians@eskimo.com) Version : 1.18d, 16-Mar-95 Description : Matrix oriented, interactive programing environment. Rlab is _not_ a clone of languages such as those used by tools like MATLAB or matrix_X/Xmath. However, as Rlab focuses on creating a good experimental environment (or laboratory) in which to do matrix math, it can be called "MATLAB-like" since its programming language possesses similar operators and concepts. Extensive use has been made of the LAPACK, FFTPACK and RANLIB sources available

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Comments

from netlib. : Includes online help and LaTeX manual. There is a mailing list. The distribution is under GPL

Name : robot Description : a scientific graph plotting and data analysis package. Works for Xview v3, and knows to generates postscript. Where : in pub/astrod on ftp.astro.psu.edu (128.118.147.28) Version : v0.46, 7 Feb 1993 Author : Robin Corbet (corbet@astro.psu.edu)

Name Where Description Author Version

: : : : :

rpart (113799 bytes) in general on Statlib Routines for recursive partitioning Terry Therneau, therneau@mayo.edu 9 July 1993

Name Where Description Language Author Version

: : : : : :

sa.tar.gz (30473 bytes) in pub/C-numanal on usc.edu library for simulated annealing versions for C, C++ and Ada exist. Works with g++ 2.4.2. Skip Carter (skip@taygeta.oc.nps.navy.mil) 3 July 1993

Name : sabre.tar.Z (813499 bytes) Where : in pub on athena.erc.msstate.edu -Ajay Shah, (213)749-8133, ajayshah@rcf.usc.edu Path: senator-bedfellow.mit.edu!bloombeacon.mit.edu!apollo.hp.com!lf.hp.com!news.dtc.hp.com!col.hp.com!usenet.eel.ufl.edu!news.mathworks.com!zom bie.ncsc.mil!nntp.coast.net!chi-news.cic.net!usc!usc!not-for-mail From: ajayshah@cmie.ernet.in Newsgroups: comp.lang.c,comp.lang.c++,sci.math.num-analysis,sci.comp-aided,sci.op-research

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Subject: Part 3 of 3: Free C,C++ for numerical computation Followup-To: sci.math.num-analysis Date: 6 Mar 1996 05:24:42 -0800 Organization: Centre for Monitoring Indian Economy, Bombay, India Lines: 547 Sender: ajayshah@almaak.usc.edu Distribution: world Message-ID: <4hk3mq$3io@almaak.usc.edu> Reply-To: ajayshah@cmie.ernet.in NNTP-Posting-Host: almaak.usc.edu Keywords: source code, numerical statistical scientific computation Xref: senator-bedfellow.mit.edu comp.lang.c:177131 comp.lang.c++:176396 sci.math.num-analysis:26783 sci.comp-aided:1260 sci.op-research:5413 Description : (not clear) a linear/nonlinear simulation system Comments : the `portable math library' directory is definitely very useful (5k lines). I noticed some interesting interpolation, integration, banded LU decomposition, nonlinear solver, etc. Author : ? Version : ?

Name Authors Description Systems Where Language Version Comments

: : : : : : : :

Scilab scilab@inria.fr Matrix--based scientific computation Sun, RS6000, HP9000, Mips, Alpha, i386 (Linux) Requires X. ftp.inria.fr (192.93.2.54) in INRIA/Projects/Meta2/Scilab ? 2.1 Resembles Matlab and Xmath. Has hundreds of builtin mathematical functions, sophisticated data structures, a high--level interpreter, a macro language, and excellent graphics. C and fortran functions can be added as new functions. Comes with toolboxes for control and signal processing, and for analysis of graphs and optimisation of utility networks.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Date

: 8 March 1995

Name Where Systems Language Description Author Version

: : : : :

sdeint.tar.z in pub/C-numanal on usc.edu Unix, MS-DOS C++ A Runge-Kutta like class for integrating systems of Stochastic Differential Equations : Skip Carter, skip@taygeta.oc.nps.navy.mil : v1.9 4 May 1993

Name Authors Description Where

: : : :

sga-c David Goldberg C source for simple genetic algorithm ftp://ftp.dcs.warwick.ac.uk/pub/mirrors/EC/GA/src/sga-c.tar.gz

Name : sge.shar Where : in c on Netlib Description : Linpack functions geco, gefa, gesl and a little of BLAS; nonstandard matrices Author : Mark K. Seager, seager@lll-crg.llnl.gov Version : April 88

Name Description Author Where Version Comments

: : : : : :

SGPC Simple Genetic Programming in C Walter Alden Tackett (tackett@ipld01.hac.com) in the pub/Users/tackett on sfi.santafe.edu 28 May 1993 genetic algorithms, nonlinear maximisation

Name Author Systems

: SIMATH : SIMATH-Gruppe, Saarbruecken, Germany : Unix

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Where

: via anonymous ftp: ftp.math.uni-sb.de (134.96.32.23), ftp.math.orst.edu (128.193.80.160) in pub/simath Version : 3.6.1 Description : SIMATH contains a lot of C-functions over algebraic structures as arbitrary long integers, rational numbers, polynomials, Galois fields, matrices, elliptic curves, algebraic number fields, modular integers, etc. There is also an interactive calculator (simath) which uses the C-libraries of SIMATH. Comments : version 3.6.1 contains a handbook written in English. The SIMATH package also includes a user interface, which makes it possible to use the on-line documentation of the functions and the keyword index. It is free, but you have to first register, in order to get a "license" file without which it won't compile.

Name Authors Description Systems Where Language

: : : : : :

simlab ? circuit simulation environment Unix, optimised version for connection machine exists. rle-vlsi.mit.edu:/pub/simlab C

Name Author Description Where Language Version

: : : :

simpack-2.1.tar.Z (287965 bytes), simpack-2.1++.tar.Z (82683 bytes) Paul A. Fishwick, fishwick@cis.ufl.edu tools for writing simulations with a EECS bias pub/simdigest/tools on bikini.cis.ufl.edu, also see tr92-022.ps.Z from cis/tech-reports/tr92 : C and C++ versions exist : v2.0, June 1992

Name Author Version Description

: : : :

smirnov.shar.Z (3599 bytes) David Rapoport (actize@cea.berkeley.edu) 22 February 1993 Kolmogorov Smirnov two-sample statistic

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Where

: in pub/C-numanal on usc.edu

Name : SMMS (Sparse Matrix Manipulation System) Description : A collection of about 80 commands to do almost anything you wish to do with sparse matrices VERY EASILY. It is designed as an instructional and prototyping tool, not for "production" work. Where : /pub/smms93/* on eceserv0.ece.wisc.edu Systems : Any Unix system with X-windows, but tested only on Sun, HP and DEC. Also works under DOS Language : Mostly C (any version). One or two routines in Fortran Author : Fernando Alvarado (alvarado@engr.wisc.edu) Version : Release 2 May 1993 Comments : Includes online help for every command and LaTeX and PostScript versions a manual. Expandable by the user. Release 2 handles complex sparse matrices, interval matrices, blocked matrices adn symbolic matrices. Visualization tools. Interfaces to Harwell routines and Boeing-Harwell sparse matrix data.

Name : smooth.tar.Z Description : Unix tool for smoothing Where : in ftp-raimund/pub/src/Math on nestroy.wu-wien.ac.at (137.208.3.4) Author : Bill Davidsen (davisen@crd.ge.com) Version : v1.9, 15 Aug 1989

Name Authors

: smoothwb (209947 bytes) : Lise Manchester (lise@cs.dal.ca) David Trueman (david@cs.dal.ca) Description : Smoothing Workbench Systems : Unix + Xview (e.g. SunOS, Linux) Where : in general on statlib Language : C (2613 lines) and fortran (1458 lines) Comments : interactive program for exploring smoothing methods

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Date

Includes postscript documentation. : 28 June 1993

Name Where Description Author

: : : :

SPARSE in sparse on Netlib library for LU factorisation for large sparse matrices Ken Kundert, Alberto Sangiovanni-Vincentelli, sparse@ic.berkeley.edu

Name : spline29.zip Where : in mirrors/msdos/c on wuarchive.wustl.edu Description : Interpolation using splines under tension, dressed up as a Unix tool Author : James. R. Van Zandt Version : v2.9, 21 Nov 1992

Name Where Description Author Version Systems Comments

: : : : : : :

|STAT in pub/stat on archive.cis.ohio-state.edu (128.146.8.52) collection of around 30 Unix tools for statistical analysis Gary Perlman (perlman@cis.ohio-state.edu) 5.4, 27 May 1993 Unix, MS-DOS Has been in use for 13 years. There is a troff|ps manual and man pages. Explicitly designed to work with Unix philosophy. The file stat.tar.Z.crypt.uu is ENCRYPTED; you have to send email asking for the password. There is a handbook available.

Name Where Description Author Version

: : : : :

submit1 in jcgs on Statlib damped convex minorant algorithm David Eberly, eberly@cs.unc.edu May 1992

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name : surf Authors : Weimin Zhao, wzhao@Nimitz.mcs.kent.edu Description : Xlib program to debug, monitor, control largescale numerical simulations (in either fortran or C). Does realtime 3d display. Systems : Aix, HP-UX, Linux. Where : sunsite.unc.edu, pub/Linux/Incoming Version : 1.0, 12 May 1994

Name Where Systems Language Description

Author Version

: : : : : : : : : : : : :

SVDPACKC.tar.Z in pub/berry on cs.utk.edu Sun, IBM RS/6000, HP9000, DECstation, Macintosh II/fx, Cray Y-MP C an ANSI-C library for the singular value decomposition of large sparse matrices. Lanczos- and subspace iteratonbased methods are used to iteratively compute several of the largest (or smallest) singular values and corresponding singular vectors. Sample UNIX C-SHELL scripts are provided for automatic compiling and testing of the library routines. Cray Y-MP compatible routines provided. Michael W. Berry (berry@cs.utk.edu) 1.0, June 1993

Name Where Description Author Version

: : : :

svd.c.Z (8704 bytes) in pub/C-numanal on usc.edu SVD based on pascal from J. C. Nash book Bryant Marks (bryant@sioux.stanford.edu) Brian Collett (bcollett@hamilton.edu) : 14 April 1993

Name : taranto-1.0.shar.Z Where : in prog/libraries on ftp.inria.fr (128.93.1.26) Description : portable, accurate FP to decimal conversion.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name Where Description Date

: : : :

totinfo in volume7 of comp.sources.misc info statistic and chi-square for 2-D contingency tables August 1989

Name Authors Description Systems Where Language Version Comments

: : : : : : : :

Tela Tensor Language Unix (SGI, Linux, Aix, Sun) ftp.funet.fi:pub/sci/math/tela/ 1.21, 24 Feb 1995 Includes a C translation of FFTPACK, 20-page user manual, FAQ, graphics examples, etc. See http://www.geo.fmi.fi/prog/tela.html Email addresses are tela-bugs@fmi.fi and tela-suggestions@fmi.fi

Name Authors Description Systems Where Language Date

: : : : :

Tensor.tar.Z E. Robert Tisdale, edwin@maui.cs.ucla.edu Experimental Tensor Class Solaris ftp://pink.cs.ucla.edu/pub/Tensor.tar.Z pink.cs.ucla.edu is 131.179.64.80 : Gnu C++ 2.6.2 : Thu Jan 12 18:10:53 GMT+0530 1995

Name Where Systems Description Author Version

: : : : : :

tsp ftp://ftp.alumni.caltech.edu/pub/dank/tsp.c Any C environment Simple heuristic Travelling Salesman Problem solver Dan Kegel - from "Discrete Optimization Algorithms," Maciej Syslo 1.1

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Name Where Systems Language Authors

tsp_solve e-mail request to churritz@crash.cts.com Borland, sco and Sun with gcc C++ Chad Hurwitz (churritz@crash.cts.com) Robert.J.Craig (kat3@uscbu.ih.att.com) and anyone else who'd like to test their own TSP tour finder's performance Version : 1.0beta Description : Finds Optimal and Heuristic Solutions to many types of Traveling Salesman Problems (TSP). Comments : tsp_solve finds optimal solutions to geometric TSPs with 100 cities in about an hour (don't go to lenscrafters for this one.) It will soon have an asymmetric TSP optimal solution finder that will perform at approximately the same level.

: : : : :

Name Where Systems Language Author Version Description Comments

: : : : : : :

UDouble ftp://beowulf.jpl.nasa.gov/pub/manning Source code: should be portable (developed with gnu gcc) C++ Evan M. Manning, manning@alumnni.caltech.edu 1.00 A class library for tracking propagation of uncertainties through systems of equations. : Described in part in an article in the March issue of the _C/C++_Users_Journal_.

Name Where Description Author Version

: : : : :

using-lapack.Z (8478 bytes) pub/C-numanal on usc.edu Notes on using Lapack through f2c. S. Sullivan (sullivan@mathcom.com) 14 April 1993

Name Where Systems

: vis5d : vis5d.ssec.wisc.edu (128.104.231.66) : SGI, Stardent, IBM PC

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Language Authors Version Description Comments

: : : :

C, Fortran Brian Paul (bpaul@vms.macc.wisc.edu) and Bill Hibbard 3.0 (soon to be 3.1) visualizing/animating data made by numerical weather models and similar sources : vis5d interactively provides 3-D isosurfaces, vector-field slices, horizontal and vertical contour and colored slices, and ribbon "particle" trajectories (integral curves)

Name : vregion Authors : Seth Teller, seth@tachyon.princeton.edu Description : Computes the voronoi diagram, delaunay triangulation, and convex hull of a two-dimensional point set. It's based on Steve Fortune's algorithm, and partially on his implementation. Systems : Unix Where : comp.sources.misc, volume 41, issue 30 Language : C Date : 14 December 1993

Name : vspline Where : in gcv on Netlib Description : non-parametric estimate of a smooth vector-valued function from noisy data Author : Jeff Fessler Comments : splines

Name Where

: wavethresh (wavelet.shar) : in directory S on Statlib, and anonymous ftp from gdr.bath.ac.uk, in directory pub/masgpn Language : C (and S functions) Author : Guy Nason (gpn@maths.bath.ac.uk) Version : 2.1 (March 26 1993) Description : wavelet transform & thresholding software in C for linking into S.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Comments

: Performs 1- and 2-D discrete wavelet transforms using Daubechie's wavelets. Also performs thresholding according to Donoho and Johnstone.

Name Where Description Author Version Comments

: : : : : :

weisfeld-simplex.shar (7457 bytes) pub/C-numanal on usc.edu small implementation of simplex method for linear programming. Matt Weisfeld (not on Internet) Feb 1993 associated with article in Feb 1993 CUJ. For production use (where you want a black-box solver), the `lpsolve' package (above) is better. If you want to open up a simplex implementation and modify it, then this is quite good, using the article as documentation.

Name Where Systems Description Author

: : : : :

Date Comments

xgobi in general on Statlib Unix, needs X Windows a data analysis package emphasising graphical data exploration Debby Swayne, dfs@bellcore.com Dianne Cook, dcook@fisher.rutgers.edu Andreas Buja, andreas@bellcore.com : 23 March 1993 : EDA

Name Where Systems Description Author Version Comments

: : : : : : :

XLispStat pub/xlispstat on umnstat.stat.umn.edu Unix, Macintosh, MSW a statistical package Luke Tierney, luke%umnstat@umn-cs.cs.umn.edu object-oriented, EDA, graphics, lisp

Name

: xtrap.c.Z (4463 bytes)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Author : Bryan M. Gorman, gorman@scri.fsu.edu Version : 28 July 1992 Description : extrapolation program. Supports 6 algorithms: VBS approximants, Aitken delta-squared, Wynn epsilon algo, Wynn rho algo, Brezenski theta algo, Levin u-transform. Is dressed up as a Unix tool. Where : pub/C-numanal on usc.edu

Name Where Systems Description Author Version Comments

: : : : : :

xvgr/xmgr (open look or motif versions) /CCALMR/pub/acegr on amb4.ccalmr.ogi.edu Unix, with either open look or motif graphics for EDA Paul J. Turner, pturner@amb4.ccalmr.ogi.edu 2.10, 2 May 1993 3.01 (Motif only), 17 August 1994. : Linux and SunOS 4.1.3 binaries are in bin directory

Name: Author: Version: Date: Description:

Yorick David Munro - Lawrence Livermore National Laboratory munro@icf.llnl.gov 1.1 18 May 1995 Yorick is a very fast interpreted language designed for scientific computing and numerical analysis. The syntax is similar to C, but without declarative statements. Operations between arrays yield array results, and Yorick provides a very rich selection of multi-dimensional array indexing operations. Yorick also features a binary I/O package which automatically translates floating point and integer representations on the machine where it is running to and from the format of any other machine. Thus, you can easily share binary files between, for example, Cray YMPs and DEC alphas, or "teach" Yorick to read existing binary databases. Yorick also offers an interactive graphics package based on X windows. X-Y plots, quadrilateral meshes, filled meshes, cell arrays, and contours are

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Language: Keywords: Where:

Systems:

supported. Finally, you can embed compiled routines in custom versions of Yorick to solve problems for which the interpreter is too slow. The primary use of Yorick to date has been as a pre- and post-processor for large physical simulation programs. A binary distribution for Linux is available at sunsite. Freely Redistributable ANSI C (some support for Fortran customization) interpreter, language, interactive graphics, data analysis, post-processing ftp-icf.llnl.gov /pub/Yorick 1.4 MB yorick-1.1.tar.gz or wuarchive.wustl.edu /languages/yorick Sun SPARC (SunOS or Solaris), HP PA-RISC (HPUX), IBM RS/6000 (AIX), DEC alpha, SGI (IRIX), Cray YMP (UNICOS), Ix86 (Linux) Requires ANSI C compiler. Interactive graphics requires X window system. Tested on Sun (SunOS and Solaris), HP PA-RISC, IBM RS/6000, DEC alpha, SGI, Cray YMP, and Linux; should not be difficult to build on other UNIX machines.

f2c --In case you had not already noticed it: a public domain, industrial strength, fortran-to-C translator named f2c exists. It has one great strength and one great weakness: "It is a true compiler". Thus the code generated always "works", at the price of frequently looking like fortran. A lot of useful fortran libraries can readily be turned into working C using f2c, and the resulting C can often be made almost human after some hand-editing. The weakest link of f2c is code which involves matrices. A pointer to f2c is at EOF. f2c is also inside Netlib, so you are probably better off figuring out how to use Netlib.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Other pointers -------------There is a lot of interesting C source in these fields which I know nothing about: - signal processing - pattern recognition, neural networks The comp.dsp FAQ has some pointers to source code. Please send me complete entries to include in the above index. A lot of 3rd party source code which hooks into the S statistical package uses computational engines written in C. With a little work you can extract useful source from this. Look in the S directory on Statlib for more pointers. If you find something which is remarkably useful and easy to extract, please tell me about it. The same phenomenon operates to some extent for the XLispStat package. Look around on the umnstat.stat.umn.edu site.

Interesting sites ----------------If you don't have ftp access, send email to ftpmail@decwrl.dec.com saying "help". You will get instructions on how to do ftp via email. Juhana Kouhia (jk87377@cs.tut.fi) has setup a very nice service: Everything in this index (except for what is on {net,stat}lib) is mirrored in pub/sci/math/numcomp-free-c on nic.funet.fi Note: this site is in finland. If you are in the US, please try to find a site closer to you. source-code newsgroups: ftp.uu.net (e.g. usenet/comp.sources.reviewed archives the comp.sources.reviewed newsgroup).

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

f2c: netlib/f2c on netlib.att.com pub/gnu on prep.ai.mit.edu Netlib: netlib.att.com email, ftp ornl.gov email, xnetlib nac.no email, xnetlib for Europe (e.g. send email to netlib@ornl.gov to access by email) unix.hensa.ac.uk is a mail server useful for Europe. ci.cs.uow.edu.au (130.130.64.3) in Australia Statlib: lib.stat.cmu.edu (as statlib) dmssyd.syd.dms.csiro.au (130.155.96.1) others: qiclab.scn.rain.com has a small collection in pub/math, including fft stuff not listed above. elib.ZIB-Berlin.de is quite interesting too. Credits ------The following people helped me put this index together: Bardo Muller David E. Stewart Skip Carter John Gregory John Eaton P. G. Hamer Alan Magnuson David Rapoport Peter Fraenkel Martin-D. Lacasse Matthew Koebbe Nicolas Ratier Henri Cohen Bill Hutchison bardo@gonzales.ief-paris-sud.fr des@thrain.anu.edu.au skip@taygeta.oc.nps.navy.mil http://taygeta.oc.nps.navy.mil/skips_home.html jwg@db.cray.com jwe@che.utexas.edu P.G.Hamer@bnr.co.uk awm@osc.edu actize@garnet.berkeley.edu pnf@pwcm.com isaac@physics.mcgill.ca phaedrus@alioth.cc.nps.navy.mil ratier@laas.laas.fr cohen@merak.greco-prog.fr bhutchi@godiva.ssw.com

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Ronald F. Guilmette Jay Han Van Snyder Alan Cabrera Vincent Broman Piercarlo Grandi Abed Hammoud Richard A. O'Keefe Fumiaki Kamiya Keith Briggs Brian Glendenning Bill Gropp Emmett McLean Wenfu Ku Adrian Ireland Alexander Frink Douglas N Arnold Jens Ehlers Bruce Haggerty Peter Espen M J Olesen Vincent Broman Luiz Henrique de Figueiredo Jose E. Korneluk

segfault!rfg@netcom.com han@corto.inria.fr vsnyder@math.Jpl.Nasa.Gov adc@tardis.cl.msu.edu broman@peanuts.nosc.mil pcg@aberystwyth.ac.uk abed@saturn.wustl.edu ok@goanna.cs.rmit.OZ.AU kamiya@slinky.cs.nyu.edu Keith.Briggs@physics.uwa.edu.au bglenden@colobus.CV.NRAO.EDU gropp@mcs.anl.gov emclean@sfsuvax1.sfsu.edu wk02@lehigh.edu aireland@hsc.usc.edu FRINK@MZDMZA.ZDV.UNI-MAINZ.DE dna@math.psu.edu je@ganymed.mt2.tu-harburg.de haggerty@acf2.NYU.EDU espen@math.unm.edu olesen@weber.me.queensu.ca broman@nosc.mil lhf@csg.uwaterloo.ca jkornel@sfwmd.gov

Of course, we owe infinite gratitude to the authors themselves, for making their work available in the public domain. -Ajay Shah, (213)749-8133, ajayshah@rcf.usc.edu

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

comp.lang.c Answers to Frequently Asked Questions (FAQ List)


From: scs@eskimo.com (Steve Summit) Newsgroups: comp.lang.c,comp.lang.c.moderated,comp.answers,news.answers Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List) Followup-To: poster Date: 1 Mar 2002 11:00:14 GMT Organization: better late than never Expires: 3 Apr 2002 00:00:00 GMT Message-ID: <2002Mar01.0600.scs.0001@eskimo.com> Reply-To: scs@eskimo.com X-Trace: eskinews.eskimo.com 1014980414 11540 204.122.16.13 (1 Mar 2002 11:00:14 GMT) X-Complaints-To: abuse@eskimo.com NNTP-Posting-Date: 1 Mar 2002 11:00:14 GMT X-Last-Modified: February 7, 1999 X-Archive-Name: C-faq/faq X-Version: 3.5 X-URL: http://www.eskimo.com/~scs/C-faq/top.html X-PGP-Signature: Version: 2.6.2 iQCSAwUBNr5mkN6sm4I1rmP1AQEr/APoniUefFSgXsFWaMy+nDcCCzvH9phH7BVx 0CwFcGKz/udQ6DsXSynb3d9i50DUeRUXP2RcY69dmV41SZrBraQmXjjlwAulRlqB mDzL9zAhlQOSaS33s6zYmUB4A4kq+61XRYGGFwBc5dSWCzTlzxbl1nWo5Uru+azJ 9MKtfOg= =f2Ny Archive-name: C-faq/faq Comp-lang-c-archive-name: C-FAQ-list URL: http://www.eskimo.com/~scs/C-faq/top.html [Last modified February 7, 1999 by scs.] This article is Copyright 1990-1999 by Steve Summit. Content from the

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

book _C Programming FAQs: Frequently Asked Questions_ is made available here by permission of the author and the publisher as a service to the community. It is intended to complement the use of the published text and is protected by international copyright laws. The content is made available here and may be accessed freely for personal use but may not be republished without permission. Certain topics come up again and again on this newsgroup. They are good questions, and the answers may not be immediately obvious, but each time they recur, much net bandwidth and reader time is wasted on repetitive responses, and on tedious corrections to the incorrect answers which are inevitably posted. This article, which is posted monthly, attempts to answer these common questions definitively and succinctly, so that net discussion can move on to more constructive topics without continual regression to first principles. No mere newsgroup article can substitute for thoughtful perusal of a full-length tutorial or language reference manual. Anyone interested enough in C to be following this newsgroup should also be interested enough to read and study one or more such manuals, preferably several times. Some C books and compiler manuals are unfortunately inadequate; a few even perpetuate some of the myths which this article attempts to refute. Several noteworthy books on C are listed in this article's bibliography; see also questions 18.9 and 18.10. Many of the questions and answers are cross-referenced to these books, for further study by the interested and dedicated reader. If you have a question about C which is not answered in this article, first try to answer it by checking a few of the referenced books, or by asking knowledgeable colleagues, before posing your question to the net at large. There are many people on the net who are happy to answer questions, but the volume of repetitive answers posted to one question, as well as the growing number of questions as the net attracts more readers, can become oppressive. If you have questions or comments prompted by this article, please reply by mail rather than following up -this article is meant to decrease net traffic, not increase it.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Besides listing frequently-asked questions, this article also summarizes frequently-posted answers. Even if you know all the answers, it's worth skimming through this list once in a while, so that when you see one of its questions unwittingly posted, you won't have to waste time answering. (However, this is a large and heavy document, so don't assume that everyone on the newsgroup has managed to read all of it in detail, and please don't roll it up and thwack people over the head with it just because they missed their answer in it.) This article was last modified on February 7, 1999, and its travels may have taken it far from its original home on Usenet. It may, however, be out-of-date, particularly if you are looking at a printed copy or one retrieved from a tertiary archive site or CD-ROM. You should be able to obtain the most up-to-date copy on the web at http://www.eskimo.com/~scs/C-faq/top.html or http://www.faqs.org/faqs/ , or from one of the ftp sites mentioned in question 20.40. Since this list is modified from time to time, its question numbers may not match those in older or newer copies which are in circulation; be careful when referring to FAQ list entries by number alone. This article was produced for free redistribution. to pay anyone for a copy of it. You should not need

Other versions of this document are also available. Posted along with it are an abridged version and (when there are changes) a list of differences with respect to the previous version. A hypertext version is available on the web at the aforementioned URL. Finally, for those who might prefer a bound, hardcopy version (and even longer answers to even more questions!), a book-length version has been published by Addison-Wesley (ISBN 0-201-84519-9). This article is always being improved. your comments to scs@eskimo.com . Your input is welcomed. Send

The questions answered here are divided into several categories: 1. Declarations and Initializations

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

Structures, Unions, and Enumerations Expressions Pointers Null Pointers Arrays and Pointers Memory Allocation Characters and Strings Boolean Expressions and Variables C Preprocessor ANSI/ISO Standard C Stdio Library Functions Floating Point Variable-Length Argument Lists Strange Problems Style Tools and Resources System Dependencies Miscellaneous Bibliography Acknowledgements

(The question numbers within each section are not always continuous, because they are aligned with the aforementioned book-length version, which contains even more questions.) Herewith, some frequently-asked questions and their answers:

Section 1. Declarations and Initializations 1.1: A: How do you decide which integer type to use? If you might need large values (above 32,767 or below -32,767), use long. Otherwise, if space is very important (i.e. if there are large arrays or many structures), use short. Otherwise, use int. If well-defined overflow characteristics are important and negative values are not, or if you want to steer clear of sign-

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

extension problems when manipulating bits or bytes, use one of the corresponding unsigned types. (Beware when mixing signed and unsigned values in expressions, though.) Although character types (especially unsigned char) can be used as "tiny" integers, doing so is sometimes more trouble than it's worth, due to unpredictable sign extension and increased code size. (Using unsigned char can help; see question 12.1 for a related problem.) A similar space/time tradeoff applies when deciding between float and double. None of the above rules apply if the address of a variable is taken and must have a particular type. If for some reason you need to declare something with an *exact* size (usually the only good reason for doing so is when attempting to conform to some externally-imposed storage layout, but see question 20.5), be sure to encapsulate the choice behind an appropriate typedef. References: K&R1 Sec. 2.2 p. 34; K&R2 Sec. 2.2 p. 36, Sec. A4.2 pp. 195-6, Sec. B11 p. 257; ISO Sec. 5.2.4.2.1, Sec. 6.1.2.5; H&S Secs. 5.1,5.2 pp. 110-114. 1.4: A: What should the 64-bit type on a machine that can support it? The forthcoming revision to the C Standard (C9X) specifies type long long as effectively being at least 64 bits, and this type has been implemented by a number of compilers for some time. (Others have implemented extensions such as __longlong.) On the other hand, there's no theoretical reason why a compiler couldn't implement type short int as 16, int as 32, and long int as 64 bits, and some compilers do indeed choose this arrangement. See also question 18.15d. References: C9X Sec. 5.2.4.2.1, Sec. 6.1.2.5.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

1.7:

What's the best way to declare and define global variables and functions? First, though there can be many "declarations" (and in many translation units) of a single "global" (strictly speaking, "external") variable or function, there must be exactly one "definition". (The definition is the declaration that actually allocates space, and provides an initialization value, if any.) The best arrangement is to place each definition in some relevant .c file, with an external declaration in a header (".h") file, which is #included wherever the declaration is needed. The .c file containing the definition should also #include the same header file, so that the compiler can check that the definition matches the declarations. This rule promotes a high degree of portability: it is consistent with the requirements of the ANSI C Standard, and is also consistent with most pre-ANSI compilers and linkers. (Unix compilers and linkers typically use a "common model" which allows multiple definitions, as long as at most one is initialized; this behavior is mentioned as a "common extension" by the ANSI Standard, no pun intended. A few very odd systems may require an explicit initializer to distinguish a definition from an external declaration.) It is possible to use preprocessor tricks to arrange that a line like DEFINE(int, i); need only be entered once in one header file, and turned into a definition or a declaration depending on the setting of some macro, but it's not clear if this is worth the trouble. It's especially important to put global declarations in header files if you want the compiler to catch inconsistent declarations for you. In particular, never place a prototype

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

for an external function in a .c file: it wouldn't generally be checked for consistency with the definition, and an incompatible prototype is worse than useless. See also questions 10.6 and 18.8. References: K&R1 Sec. 4.5 pp. 76-7; K&R2 Sec. 4.4 pp. 80-1; ISO Sec. 6.1.2.2, Sec. 6.7, Sec. 6.7.2, Sec. G.5.11; Rationale Sec. 3.1.2.2; H&S Sec. 4.8 pp. 101-104, Sec. 9.2.3 p. 267; CT&P Sec. 4.2 pp. 54-56. 1.11: A: What does extern mean in a function declaration? It can be used as a stylistic hint to indicate that the function's definition is probably in another source file, but there is no formal difference between extern int f(); and int f(); References: ISO Sec. 6.1.2.2, Sec. 6.5.1; Rationale Sec. 3.1.2.2; H&S Secs. 4.3,4.3.1 pp. 75-6. 1.12: A: What's the auto keyword good for? Nothing; it's archaic. See also question 20.37.

References: K&R1 Sec. A8.1 p. 193; ISO Sec. 6.1.2.4, Sec. 6.5.1; H&S Sec. 4.3 p. 75, Sec. 4.3.1 p. 76. 1.14: I can't seem to define a linked list successfully. typedef struct { char *item; NODEPTR next; I tried

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

} *NODEPTR; but the compiler gave me error messages. contain a pointer to itself? A: Can't a structure in C

Structures in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. The problem with the NODEPTR example is that the typedef has not been defined at the point where the "next" field is declared. To fix this code, first give the structure a tag ("struct node"). Then, declare the "next" field as a simple "struct node *", or disentangle the typedef declaration from the structure definition, or both. One corrected version would be struct node { char *item; struct node *next; }; typedef struct node *NODEPTR; and there are at least three other equivalently correct ways of arranging it. A similar problem, with a similar solution, can arise when attempting to declare a pair of typedef'ed mutually referential structures. See also question 2.1. References: K&R1 Sec. 6.5 p. 101; K&R2 Sec. 6.5 p. 139; ISO Sec. 6.5.2, Sec. 6.5.2.3; H&S Sec. 5.6.1 pp. 132-3.

1.21:

How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters? The first part of this question can be answered in at least three ways:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

1. 2.

char *(*(*a[N])())(); Build the declaration up incrementally, using typedefs: typedef char *pc; typedef pc fpc(); typedef fpc *pfpc; typedef pfpc fpfpc(); typedef fpfpc *pfpfpc; pfpfpc a[N]; /* /* /* /* /* /* pointer to char */ function returning pointer to char */ pointer to above */ function returning... */ pointer to... */ array of... */

3.

Use the cdecl program, which turns English into C and vice versa: cdecl> declare a as array of pointer to function returning pointer to function returning pointer to char char *(*(*a[])())() cdecl can also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions, like the one above). See question 18.1.

Any good book on C should explain how to read these complicated C declarations "inside out" to understand them ("declaration mimics use"). The pointer-to-function declarations in the examples above have not included parameter type information. When the parameters have complicated types, declarations can *really* get messy. (Modern versions of cdecl can help here, too.) References: K&R2 Sec. 5.12 p. 122; ISO Sec. 6.5ff (esp. Sec. 6.5.4); H&S Sec. 4.5 pp. 85-92, Sec. 5.10.1 pp. 149-50. 1.22: How can I declare a function that can return a pointer to a function of the same type? I'm building a state machine with

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

one function for each state, each of which returns a pointer to the function for the next state. But I can't find a way to declare the functions. A: You can't quite do it directly. Either have the function return a generic function pointer, with some judicious casts to adjust the types as the pointers are passed around; or have it return a structure containing only a pointer to a function returning that structure. My compiler is complaining about an invalid redeclaration of a function, but I only define it once and call it once. Functions which are called without a declaration in scope (perhaps because the first call precedes the function's definition) are assumed to be declared as returning int (and without any argument type information), leading to discrepancies if the function is later declared or defined otherwise. Non-int functions must be declared before they are called. Another possible source of this problem is that the function has the same name as another one declared in some header file. See also questions 11.3 and 15.1. References: K&R1 Sec. 4.2 p. 70; K&R2 Sec. 4.2 p. 72; ISO Sec. 6.3.2.2; H&S Sec. 4.7 p. 101. 1.25b: What's the right declaration for main()? Is void main() correct? A: 1.30: See questions 11.12a to 11.15. (But no, it's not correct.)

1.25:

A:

What am I allowed to assume about the initial values of variables which are not explicitly initialized? If global variables start out as "zero", is that good enough for null pointers and floating-point zeroes?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Uninitialized variables with "static" duration (that is, those declared outside of functions, and those declared with the storage class static), are guaranteed to start out as zero, as if the programmer had typed "= 0". Therefore, such variables are implicitly initialized to the null pointer (of the correct type; see also section 5) if they are pointers, and to 0.0 if they are floating-point. Variables with "automatic" duration (i.e. local variables without the static storage class) start out containing garbage, unless they are explicitly initialized. (Nothing useful can be predicted about the garbage.) Dynamically-allocated memory obtained with malloc() and realloc() is also likely to contain garbage, and must be initialized by the calling program, as appropriate. Memory obtained with calloc() is all-bits-0, but this is not necessarily useful for pointer or floating-point values (see question 7.31, and section 5). References: K&R1 Sec. 4.9 pp. 82-4; K&R2 Sec. 4.9 pp. 85-86; ISO Sec. 6.5.7, Sec. 7.10.3.1, Sec. 7.10.5.3; H&S Sec. 4.2.8 pp. 723, Sec. 4.6 pp. 92-3, Sec. 4.6.2 pp. 94-5, Sec. 4.6.3 p. 96, Sec. 16.1 p. 386.

1.31:

This code, straight out of a book, isn't compiling: int f() { char a[] = "Hello, world!"; }

A:

Perhaps you have a pre-ANSI compiler, which doesn't allow initialization of "automatic aggregates" (i.e. non-static local arrays, structures, and unions). (As a workaround, and depending on how the variable a is used, you may be able to make it global or static, or replace it with a pointer, or initialize it by hand with strcpy() when f() is called.) See also

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

question 11.29. 1.31b: What's wrong with this initialization? char *p = malloc(10); My compiler is complaining about an "invalid initializer", or something. A: Is the declaration of a static or non-local variable? Function calls are allowed only in initializers for automatic variables (that is, for local, non-static variables). What is the difference between these initializations? char a[] = "string literal"; char *p = "string literal"; My program crashes if I try to assign a new value to p[i]. A: A string literal can be used in two slightly different ways. As an array initializer (as in the declaration of char a[]), it specifies the initial values of the characters in that array. Anywhere else, it turns into an unnamed, static array of characters, which may be stored in read-only memory, which is why you can't safely modify it. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element. (For compiling old code, some compilers have a switch controlling whether strings are writable or not.) See also questions 1.31, 6.1, 6.2, and 6.8. References: K&R2 Sec. 5.5 p. 104; ISO Sec. 6.1.4, Sec. 6.5.7; Rationale Sec. 3.1.4; H&S Sec. 2.7.4 pp. 31-2.

1.32:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

1.34:

I finally figured out the syntax for declaring pointers to functions, but now how do I initialize one? Use something like extern int func(); int (*fp)() = func; When the name of a function appears in an expression like this, it "decays" into a pointer (that is, it has its address implicitly taken), much as an array name does. An explicit declaration for the function is normally needed, since implicit external function declaration does not happen in this case (because the function name in the initialization is not part of a function call). See also questions 1.25 and 4.12.

A:

Section 2. Structures, Unions, and Enumerations 2.1: What's the difference between these two declarations? struct x1 { ... }; typedef struct { ... } x2; A: The first form declares a "structure tag"; the second declares a "typedef". The main difference is that you subsequently refer to the first type as "struct x1" and the second simply as "x2". That is, the second declaration is of a slightly more abstract type -- its users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it. Why doesn't struct x { ... }; x thestruct;

2.2:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

work? A: C is not C++. Typedef names are not automatically generated for structure tags. See also question 2.1 above. Can a structure contain a pointer to itself? Most certainly. See question 1.14.

2.3: A: 2.4:

What's the best way of implementing opaque (abstract) data types in C? One good way is for clients to use structure pointers (perhaps additionally hidden behind typedefs) which point to structure types which are not publicly defined. I came across some code that declared a structure like this: struct name { int namelen; char namestr[1]; }; and then did some tricky allocation to make the namestr array act like it had several elements. Is this legal or portable?

A:

2.6:

A:

This technique is popular, although Dennis Ritchie has called it "unwarranted chumminess with the C implementation." An official interpretation has deemed that it is not strictly conforming with the C Standard, although it does seem to work under all known implementations. (Compilers which check array bounds carefully might issue warnings.) Another possibility is to declare the variable-size element very large, rather than very small; in the case of the above example: ...

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

char namestr[MAXSIZE]; where MAXSIZE is larger than any name which will be stored. However, it looks like this technique is disallowed by a strict interpretation of the Standard as well. Furthermore, either of these "chummy" structures must be used with care, since the programmer knows more about their size than the compiler does. (In particular, they can generally only be manipulated via pointers.) C9X will introduce the concept of a "flexible array member", which will allow the size of an array to be omitted if it is the last member in a structure, thus providing a well-defined solution. References: Rationale Sec. 3.5.4.2; C9X Sec. 6.5.2.1. 2.7: I heard that structures could be assigned to variables and passed to and from functions, but K&R1 says not. What K&R1 said (though this was quite some time ago by now) was that the restrictions on structure operations would be lifted in a forthcoming version of the compiler, and in fact structure assignment and passing were fully functional in Ritchie's compiler even as K&R1 was being published. A few ancient C compilers may have lacked these operations, but all modern compilers support them, and they are part of the ANSI C standard, so there should be no reluctance to use them. (Note that when a structure is assigned, passed, or returned, the copying is done monolithically; the data pointed to by any pointer fields is *not* copied.) References: K&R1 Sec. 6.2 p. 121; K&R2 Sec. 6.2 p. 129; ISO Sec. 6.1.2.5, Sec. 6.2.2.1, Sec. 6.3.16; H&S Sec. 5.6.2 p. 133. 2.8: Is there a way to compare structures automatically?

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

No. There is no single, good way for a compiler to implement implicit structure comparison (i.e. to support the == operator for structures) which is consistent with C's low-level flavor. A simple byte-by-byte comparison could founder on random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct; see question 2.12). A field-by-field comparison might require unacceptable amounts of repetitive code for large structures. If you need to compare two structures, you'll have to write your own function to do so, field by field. References: K&R2 Sec. 6.2 p. 129; Rationale Sec. 3.3.9; H&S Sec. 5.6.2 p. 133.

2.10:

How can I pass constant values to functions which accept structure arguments? As of this writing, C has no way of generating anonymous structure values. You will have to use a temporary structure variable or a little structure-building function. The C9X Standard will introduce "compound literals"; one form of compound literal will allow structure constants. For example, to pass a constant coordinate pair to a plotpoint() function which expects a struct point, you will be able to call plotpoint((struct point){1, 2}); Combined with "designated initializers" (another C9X feature), it will also be possible to specify member values by name: plotpoint((struct point){.x=1, .y=2}); See also question 4.10. References: C9X Sec. 6.3.2.5, Sec. 6.5.8.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

2.11: A:

How can I read/write structures from/to data files? It is relatively straightforward to write a structure out using fwrite(): fwrite(&somestruct, sizeof somestruct, 1, fp); and a corresponding fread invocation can read it back in. However, data files so written will *not* be portable (see questions 2.12 and 20.5). Note also that if the structure contains any pointers, only the pointer values will be written, and they are most unlikely to be valid when read back in. Finally, note that for widespread portability you must use the "b" flag when fopening the files; see question 12.38. A more portable solution, though it's a bit more work initially, is to write a pair of functions for writing and reading a structure, field-by-field, in a portable (perhaps even humanreadable) way. References: H&S Sec. 15.13 p. 381.

2.12:

My compiler is leaving holes in structures, which is wasting space and preventing "binary" I/O to external data files. Can I turn off the padding, or otherwise control the alignment of structure fields? Your compiler may provide an extension to give you this control (perhaps a #pragma; see question 11.20), but there is no standard method. See also question 20.5. References: K&R2 Sec. 6.4 p. 138; H&S Sec. 5.6.4 p. 135.

A:

2.13:

Why does sizeof report a larger size than I expect for a structure type, as if there were padding at the end?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Structures may have this padding (as well as internal padding), if necessary, to ensure that alignment properties will be preserved when an array of contiguous structures is allocated. Even when the structure is not part of an array, the end padding remains, so that sizeof can always return a consistent size. See also question 2.12 above. References: H&S Sec. 5.6.7 pp. 139-40.

2.14:

How can I determine the byte offset of a field within a structure? ANSI C defines the offsetof() macro, which should be used if available; see <stddef.h>. If you don't have it, one possible implementation is #define offsetof(type, mem) ((size_t) \ ((char *)&((type *)0)->mem - (char *)(type *)0)) This implementation is not 100% portable; some compilers may legitimately refuse to accept it. See question 2.15 below for a usage hint. References: ISO Sec. 7.1.6; Rationale Sec. 3.5.4.2; H&S Sec. 11.1 pp. 292-3.

A:

2.15: A:

How can I access structure fields by name at run time? Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is offsetb = offsetof(struct a, b) If structp is a pointer to an instance of this structure, and field b is an int (with offset as computed above), b's value can be set indirectly with

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

*(int *)((char *)structp + offsetb) = value; 2.18: This program works correctly, but it dumps core after it finishes. Why? struct list { char *item; struct list *next; } /* Here is the main program. */ main(argc, argv) { ... } A: A missing semicolon causes main() to be declared as returning a structure. (The connection is hard to see because of the intervening comment.) Since structure-valued functions are usually implemented by adding a hidden return pointer, the generated code for main() tries to accept three arguments, although only two are passed (in this case, by the C start-up code). See also questions 10.9 and 16.4. References: CT&P Sec. 2.3 pp. 21-2. 2.20: A: Can I initialize unions? The current C Standard allows an initializer for the first-named member of a union. C9X will introduce "designated initializers" which can be used to initialize any member. References: K&R2 Sec. 6.8 pp. 148-9; ISO Sec. 6.5.7; C9X Sec. 6.5.8; H&S Sec. 4.6.7 p. 100. 2.22: What is the difference between an enumeration and a set of preprocessor #defines? At the present time, there is little difference. The C Standard

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

says that enumerations may be freely intermixed with other integral types, without errors. (If, on the other hand, such intermixing were disallowed without explicit casts, judicious use of enumerations could catch certain programming errors.) Some advantages of enumerations are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enumeration variables are examined, and that they obey block scope. (A compiler may also generate nonfatal warnings when enumerations and integers are indiscriminately mixed, since doing so can still be considered bad style even though it is not strictly illegal.) A disadvantage is that the programmer has little control over those nonfatal warnings; some programmers also resent not having control over the sizes of enumeration variables. References: K&R2 Sec. 2.3 p. 39, Sec. A4.2 p. 196; ISO Sec. 6.1.2.5, Sec. 6.5.2, Sec. 6.5.2.2, Annex F; H&S Sec. 5.5 pp. 127-9, Sec. 5.11.2 p. 153. 2.24: A: Is there an easy way to print enumeration values symbolically? No. You can write a little function to map an enumeration constant to a string. (For debugging purposes, a good debugger should automatically print enumeration constants symbolically.)

Section 3. Expressions 3.1: Why doesn't this code: a[i] = i++; work? A: The subexpression i++ causes a side effect -- it modifies i's value -- which leads to undefined behavior since i is also referenced elsewhere in the same expression, and there's no way

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

to determine whether the reference (in a[i] on the left-hand side) should be to the old or the new value. (Note that although the language in K&R suggests that the behavior of this expression is unspecified, the C Standard makes the stronger statement that it is undefined -- see question 11.33.) References: K&R1 Sec. 2.12; K&R2 Sec. 2.12; ISO Sec. 6.3; H&S Sec. 7.12 pp. 227-9. 3.2: Under my compiler, the code int i = 7; printf("%d\n", i++ * i++); prints 49. print 56? A: Regardless of the order of evaluation, shouldn't it

Although the postincrement and postdecrement operators ++ and -perform their operations after yielding the former value, the implication of "after" is often misunderstood. It is *not* guaranteed that an increment or decrement is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered "finished" (before the next "sequence point," in ANSI C's terminology; see question 3.8). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards. The behavior of code which contains multiple, ambiguous side effects has always been undefined. (Loosely speaking, by "multiple, ambiguous side effects" we mean any combination of ++, --, =, +=, -=, etc. in a single expression which causes the same object either to be modified twice or modified and then inspected. This is a rough definition; see question 3.8 for a precise one, and question 11.33 for the meaning of "undefined.") Don't even try to find out how your compiler implements such things (contrary to the ill-advised exercises in many C

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

textbooks); as K&R wisely point out, "if you don't know *how* they are done on various machines, that innocence may help to protect you." References: K&R1 Sec. 2.12 p. 50; K&R2 Sec. 2.12 p. 54; ISO Sec. 6.3; H&S Sec. 7.12 pp. 227-9; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1. 3.3: I've experimented with the code int i = 3; i = i++; on several compilers. Some gave i the value 3, and some gave 4. Which compiler is correct? A: There is no correct answer; the expression is undefined. See questions 3.1, 3.8, 3.9, and 11.33. (Also, note that neither i++ nor ++i is the same as i+1. If you want to increment i, use i=i+1, i+=1, i++, or ++i, not some combination. See also question 3.12.) Here's a slick expression: a ^= b ^= a ^= b It swaps a and b without using a temporary. A: Not portably, it doesn't. It attempts to modify the variable a twice between sequence points, so its behavior is undefined. For example, it has been reported that when given the code int a = 123, b = 7654; a ^= b ^= a ^= b; the SCO Optimizing C compiler (icc) sets b to 123 and a to 0.

3.3b:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

See also questions 3.1, 3.8, 10.3, and 20.15c. 3.4: Can I use explicit parentheses to force the order of evaluation I want? Even if I don't, doesn't precedence dictate it? Not in general. Operator precedence and explicit parentheses impose only a partial ordering on the evaluation of an expression. In the expression f() + g() * h() although we know that the multiplication will happen before the addition, there is no telling which of the three functions will be called first. When you need to ensure the order of subexpression evaluation, you may need to use explicit temporary variables and separate statements. References: K&R1 Sec. 2.12 p. 49, Sec. A.7 p. 185; K&R2 Sec. 2.12 pp. 52-3, Sec. A.7 p. 200. 3.5: But what about the && and || operators? I see code like "while((c = getchar()) != EOF && c != '\n')" ... There is a special "short-circuiting" exception for those operators. The right-hand side is not evaluated if the lefthand side determines the outcome (i.e. is true for || or false for &&). Therefore, left-to-right evaluation is guaranteed, as it also is for the comma operator. Furthermore, all of these operators (along with ?:) introduce an extra internal sequence point (see question 3.8). References: K&R1 Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R2 Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ISO Sec. 6.3.13, Sec. 6.3.14, Sec. 6.3.15; H&S Sec. 7.7 pp. 217-8, Sec. 7.8 pp.

A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

218-20, Sec. 7.12.1 p. 229; CT&P Sec. 3.7 pp. 46-7. 3.8: How can I understand these complex expressions? "sequence point"? What's a

A:

A sequence point is a point in time (at the end of the evaluation of a full expression, or at the ||, &&, ?:, or comma operators, or just before a function call) at which the dust has settled and all side effects are guaranteed to be complete. The ANSI/ISO C Standard states that Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The second sentence can be difficult to understand. It says that if an object is written to within a full expression, any and all accesses to it within the same expression must be for the purposes of computing the value to be written. This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification. See also question 3.9 below. References: ISO Sec. 5.1.2.3, Sec. 6.3, Sec. 6.6, Annex C; Rationale Sec. 2.1.2.3; H&S Sec. 7.12.1 pp. 228-9.

3.9:

So given a[i] = i++; we don't know which cell of a[] gets written to, but i does get incremented by one, right?

A:

*No*. Once an expression or program becomes undefined, *all* aspects of it become undefined. See questions 3.2, 3.3, 11.33,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

and 11.35. 3.12: If I'm not using the value of the expression, should I use i++ or ++i to increment a variable? Since the two forms differ only in the value yielded, they are entirely equivalent when only their side effect is needed. (However, the prefix form is preferred in C++.) See also question 3.3. References: K&R1 Sec. 2.8 p. 43; K&R2 Sec. 2.8 p. 47; ISO Sec. 6.3.2.4, Sec. 6.3.3.1; H&S Sec. 7.4.4 pp. 192-3, Sec. 7.5.8 pp. 199-200. 3.14: Why doesn't the code int a = 1000, b = 1000; long int c = a * b; work? A: Under C's integral promotion rules, the multiplication is carried out using int arithmetic, and the result may overflow or be truncated before being promoted and assigned to the long int left-hand side. Use an explicit cast to force long arithmetic: long int c = (long int)a * b; Note that (long int)(a * b) would *not* have the desired effect. A similar problem can arise when two integers are divided, with the result assigned to a floating-point variable; the solution is similar, too. References: K&R1 Sec. 2.7 p. 41; K&R2 Sec. 2.7 p. 44; ISO Sec. 6.2.1.5; H&S Sec. 6.3.4 p. 176; CT&P Sec. 3.9 pp. 49-50. 3.16: I have a complicated expression which I have to assign to one of

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

two variables, depending on a condition. this?

Can I use code like

((condition) ? a : b) = complicated_expression; A: No. The ?: operator, like most operators, yields a value, and you can't assign to a value. (In other words, ?: does not yield an "lvalue".) If you really want to, you can try something like *((condition) ? &a : &b) = complicated_expression; although this is admittedly not as pretty. References: ISO Sec. 6.3.15; H&S Sec. 7.1 pp. 179-180.

Section 4. Pointers 4.2: I'm trying to declare a pointer and allocate some space for it, but it's not working. What's wrong with this code? char *p; *p = malloc(10); A: The pointer you declared is p, not *p. To make a pointer point somewhere, you just use the name of the pointer: p = malloc(10); It's when you're manipulating the pointed-to memory that you use * as an indirection operator: *p = 'H'; See also questions 1.21, 7.1, 7.3c, and 8.3. References: CT&P Sec. 3.1 p. 28.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

4.3: A:

Does *p++ increment p, or what it points to? Postfix ++ essentially has higher precedence than the prefix unary operators. Therefore, *p++ is equivalent to *(p++); it increments p, and returns the value which p pointed to before p was incremented. To increment the value pointed to by p, use (*p)++ (or perhaps ++*p, if the order of the side effect doesn't matter). References: K&R1 Sec. 5.1 p. 91; K&R2 Sec. 5.1 p. 95; ISO Sec. 6.3.2, Sec. 6.3.3; H&S Sec. 7.4.4 pp. 192-3, Sec. 7.5 p. 193, Secs. 7.5.7,7.5.8 pp. 199-200.

4.5:

I have a char * pointer that happens to point to some ints, and I want to step it over them. Why doesn't ((int *)p)++; work?

A:

In C, a cast operator does not mean "pretend these bits have a different type, and treat them accordingly"; it is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++. (It is either an accident or a delibrate but nonstandard extension if a particular compiler accepts expressions such as the above.) Say what you mean: use p = (char *)((int *)p + 1); or (since p is a char *) simply p += sizeof(int); Whenever possible, you should choose appropriate pointer types in the first place, instead of trying to treat one type as another.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: K&R2 Sec. A7.5 p. 205; ISO Sec. 6.3.4; Rationale Sec. 3.3.2.4; H&S Sec. 7.1 pp. 179-80. 4.8: I have a function which accepts, and is supposed to initialize, a pointer: void f(int *ip) { static int dummy = 5; ip = &dummy; } But when I call it like this: int *ip; f(ip); the pointer in the caller remains unchanged. A: Are you sure the function initialized what you thought it did? Remember that arguments in C are passed by value. The called function altered only the passed copy of the pointer. You'll either want to pass the address of the pointer (the function will end up accepting a pointer-to-a-pointer), or have the function return the pointer. See also questions 4.9 and 4.11. 4.9: Can I use a void ** pointer as a parameter so that a function can accept a generic pointer by reference? Not portably. There is no generic pointer-to-pointer type in C. void * acts as a generic pointer only because conversions are applied automatically when other pointer types are assigned to and from void *'s; these conversions cannot be performed (the correct underlying pointer type is not known) if an attempt is made to indirect upon a void ** value which points at a pointer type other than void *.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

4.10:

I have a function extern int f(int *); which accepts a pointer to an int. reference? A call like f(&5); doesn't seem to work. How can I pass a constant by

A:

You can't do this directly. You will have to declare a temporary variable, and then pass its address to the function: int five = 5; f(&five); See also questions 2.10, 4.8, and 20.1.

4.11: A:

Does C even have "pass by reference"? Not really. Strictly speaking, C always uses pass by value. You can simulate pass by reference yourself, by defining functions which accept pointers and then using the & operator when calling, and the compiler will essentially simulate it for you when you pass an array to a function (by passing a pointer instead, see question 6.4 et al.). However, C has nothing truly equivalent to formal pass by reference or C++ reference parameters. (On the other hand, function-like preprocessor macros can provide a form of "pass by name".) See also questions 4.8 and 20.1. References: K&R1 Sec. 1.8 pp. 24-5, Sec. 5.2 pp. 91-3; K&R2 Sec. 1.8 pp. 27-8, Sec. 5.2 pp. 95-7; ISO Sec. 6.3.2.2; H&S Sec. 9.5 pp. 273-4.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

4.12:

I've seen different methods used for calling functions via pointers. What's the story? Originally, a pointer to a function had to be "turned into" a "real" function, with the * operator (and an extra pair of parentheses, to keep the precedence straight), before calling: int r, func(), (*fp)() = func; r = (*fp)(); It can also be argued that functions are always called via pointers, and that "real" function names always decay implicitly into pointers (in expressions, as they do in initializations; see question 1.34). This reasoning (which is in fact used in the ANSI standard) means that r = fp(); is legal and works correctly, whether fp is the name of a function or a pointer to one. (The usage has always been unambiguous; there is nothing you ever could have done with a function pointer followed by an argument list except call the function pointed to.) An explicit * is still allowed. See also question 1.34. References: K&R1 Sec. 5.12 p. 116; K&R2 Sec. 5.11 p. 120; ISO Sec. 6.3.2.2; Rationale Sec. 3.3.2.2; H&S Sec. 5.8 p. 147, Sec. 7.4.3 p. 190.

A:

Section 5. Null Pointers 5.1: A: What is this infamous null pointer, anyway? The language definition states that for each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

"guaranteed to compare unequal to a pointer to any object or function." That is, the address-of operator & will never yield a null pointer, nor will a successful call to malloc(). (malloc() does return a null pointer when it fails, and this is a typical use of null pointers: as a "special" pointer value with some other meaning, usually "not allocated" or "not pointing anywhere yet.") A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object or function; an uninitialized pointer might point anywhere. See also questions 1.30, 7.1, and 7.31. As mentioned above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different. Although programmers need not know the internal values, the compiler must always be informed which type of null pointer is required, so that it can make the distinction if necessary (see questions 5.2, 5.5, and 5.6 below). References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ISO Sec. 6.2.2.3; Rationale Sec. 3.2.2.3; H&S Sec. 5.3.2 pp. 121-3. 5.2: A: How do I get a null pointer in my programs? According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal: char *p = 0; if(p != 0) (See also question 5.3.)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. To generate a null pointer in a function call context, an explicit cast may be required, to force the 0 to be recognized as a pointer. For example, the Unix system call execl takes a variable-length, null-pointer-terminated list of character pointer arguments, and is correctly called like this: execl("/bin/sh", "sh", "-c", "date", (char *)0); If the (char *) cast on the last argument were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong.) When function prototypes are in scope, argument passing becomes an "assignment context," and most casts may safely be omitted, since the prototype tells the compiler that a pointer is required, and of which type, enabling it to correctly convert an unadorned 0. Function prototypes cannot provide the types for variable arguments in variable-length argument lists however, so explicit casts are still required for those arguments. (See also question 15.3.) It is probably safest to properly cast all null pointer constants in function calls, to guard against varargs functions or those without prototypes. Summary: Unadorned 0 okay: initialization assignment comparison function call, variable argument in varargs function call Explicit cast required: function call, no prototype in scope

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

prototype in scope, fixed argument References: K&R1 Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R2 Sec. A7.10 p. 207, Sec. A7.17 p. 209; ISO Sec. 6.2.2.3; H&S Sec. 4.6.3 p. 95, Sec. 6.2.7 p. 171. 5.3: Is the abbreviated pointer comparison "if(p)" to test for nonnull pointers valid? What if the internal representation for null pointers is nonzero? When C requires the Boolean value of an expression, a false value is inferred when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes if(expr) where "expr" is any expression at all, the compiler essentially acts as if it had been written as if((expr) != 0) Substituting the trivial pointer expression "p" for "expr", we have if(p) is equivalent to if(p != 0)

A:

and this is a comparison context, so the compiler can tell that the (implicit) 0 is actually a null pointer constant, and use the correct null pointer value. There is no trickery involved here; compilers do work this way, and generate identical code for both constructs. The internal representation of a null pointer does *not* matter. The boolean negation operator, !, can be described as follows: !expr is essentially equivalent to or to (expr)?0:1 ((expr) == 0)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

which leads to the conclusion that if(!p) is equivalent to if(p == 0)

"Abbreviations" such as if(p), though perfectly legal, are considered by some to be bad style (and by others to be good style; see question 17.10). See also question 9.2. References: K&R2 Sec. A7.4.7 p. 204; ISO Sec. 6.3.3.3, Sec. 6.3.9, Sec. 6.3.13, Sec. 6.3.14, Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5; H&S Sec. 5.3.2 p. 122. 5.4: A: What is NULL and how is it #defined? As a matter of style, many programmers prefer not to have unadorned 0's scattered through their programs. Therefore, the preprocessor macro NULL is #defined (by <stdio.h> and several other headers) with the value 0, possibly cast to (void *) (see also question 5.6). A programmer who wishes to make explicit the distinction between 0 the integer and 0 the null pointer constant can then use NULL whenever a null pointer is required. Using NULL is a stylistic convention only; the preprocessor turns NULL back into 0 which is then recognized by the compiler, in pointer contexts, as before. In particular, a cast may still be necessary before NULL (as before 0) in a function call argument. The table under question 5.2 above applies for NULL as well as 0 (an unadorned NULL is equivalent to an unadorned 0). NULL should *only* be used for pointers; see question 5.9. References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ISO Sec. 7.1.6, Sec. 6.2.2.3; Rationale Sec. 4.1.5; H&S Sec. 5.3.2 p. 122, Sec. 11.1 p. 292.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

5.5:

How should NULL be defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? The same as on any other machine: as 0 (or some version of 0; see question 5.4). Whenever a programmer requests a null pointer, either by writing "0" or "NULL", it is the compiler's responsibility to generate whatever bit pattern the machine uses for that null pointer. Therefore, #defining NULL as 0 on a machine for which internal null pointers are nonzero is as valid as on any other: the compiler must always be able to generate the machine's correct null pointers in response to unadorned 0's seen in pointer contexts. See also questions 5.2, 5.10, and 5.17. References: ISO Sec. 7.1.6; Rationale Sec. 4.1.5.

A:

5.6:

If NULL were defined as follows: #define NULL ((char *)0) wouldn't that make function calls which pass an uncast NULL work?

A:

Not in general. The complication is that there are machines which use different internal representations for pointers to different types of data. The suggested definition would make uncast NULL arguments to functions expecting pointers to characters work correctly, but pointer arguments of other types would still be problematical, and legal constructions such as FILE *fp = NULL; could fail. Nevertheless, ANSI C allows the alternate definition

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#define NULL ((void *)0) for NULL. Besides potentially helping incorrect programs to work (but only on machines with homogeneous pointers, thus questionably valid assistance), this definition may catch programs which use NULL incorrectly (e.g. when the ASCII NUL character was really intended; see question 5.9). References: Rationale Sec. 4.1.5. 5.9: If NULL and 0 are equivalent as null pointer constants, which should I use? Many programmers believe that NULL should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding NULL and 0 is only compounded by hiding 0 behind a macro, and prefer to use unadorned 0 instead. There is no one right answer. (See also questions 9.2 and 17.10.) C programmers must understand that NULL and 0 are interchangeable in pointer contexts, and that an uncast 0 is perfectly acceptable. Any usage of NULL (as opposed to 0) should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's. NULL should *not* be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (Furthermore, ANSI allows the definition of NULL to be ((void *)0), which will not work at all in nonpointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition #define NUL '\0' if you must.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102. 5.10: But wouldn't it be better to use NULL (rather than 0), in case the value of NULL changes, perhaps on a machine with nonzero internal null pointers? No. (Using NULL may be preferable, but not for this reason.) Although symbolic constants are often used in place of numbers because the numbers might change, this is *not* the reason that NULL is used in place of 0. Once again, the language guarantees that source-code 0's (in pointer contexts) generate null pointers. NULL is used only as a stylistic convention. See questions 5.5 and 9.2. I use the preprocessor macro #define Nullptr(type) (type *)0 to help me build null pointers of the correct type. A: This trick, though popular and superficially attractive, does not buy much. It is not needed in assignments or comparisons; see question 5.2. (It does not even save keystrokes.) See also questions 9.1 and 10.2. This is strange. pointer is not? NULL is guaranteed to be 0, but the null

A:

5.12:

5.13:

A:

When the term "null" or "NULL" is casually used, one of several things may be meant: 1. The conceptual null pointer, the abstract language concept defined in question 5.1. It is implemented with... The internal (or run-time) representation of a null pointer, which may or may not be all-bits-0 and which may be different for different pointer types. The actual values should be of concern only to compiler writers.

2.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Authors of C programs never see them, since they use... 3. The null pointer constant, which is a constant integer 0 (see question 5.2). It is often hidden behind... The NULL macro, which is #defined to be 0 (see question 5.4). Finally, as red herrings, we have... The ASCII null character (NUL), which does have all bits zero, but has no necessary relation to the null pointer except in name; and... The "null string," which is another name for the empty string (""). Using the term "null string" can be confusing in C, because an empty string involves a null ('\0') character, but *not* a null pointer, which brings us full circle...

4.

5.

6.

This article uses the phrase "null pointer" (in lower case) for sense 1, the character "0" or the phrase "null pointer constant" for sense 3, and the capitalized word "NULL" for sense 4. 5.14: Why is there so much confusion surrounding null pointers? do these questions come up so often? Why

A:

C programmers traditionally like to know more than they might need to about the underlying machine implementation. The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) may seem to suggest that the value could change some day, or on some weird machine. The construct "if(p == 0)" is easily misread as calling for conversion of p to an integral type, rather than 0 to a pointer type, before the comparison. Finally, the distinction between the several uses of the term "null" (listed in question 5.13 above) is often overlooked. One good way to wade out of the confusion is to imagine that C

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

used a keyword (perhaps "nil", like Pascal) as a null pointer constant. The compiler could either turn "nil" into the appropriate type of null pointer when it could unambiguously determine that type from the source code, or complain when it could not. Now in fact, in C the keyword for a null pointer constant is not "nil" but "0", which works almost as well, except that an uncast "0" in a non-pointer context generates an integer zero instead of an error message, and if that uncast 0 was supposed to be a null pointer constant, the code may not work. 5.15: I'm confused. stuff. I just can't understand all this null pointer

A:

Here are two simple rules you can follow: 1. When you want a null pointer constant in source code, use "0" or "NULL". If the usage of "0" or "NULL" is an argument in a function call, cast it to the pointer type expected by the function being called.

2.

The rest of the discussion has to do with other people's misunderstandings, with the internal representation of null pointers (which you shouldn't need to know), and with the complexities of function prototypes. (Taking those complexities into account, we find that rule 2 is conservative, of course; but it doesn't hurt.) Understand questions 5.1, 5.2, and 5.4, and consider 5.3, 5.9, 5.13, and 5.14, and you'll do fine. 5.16: Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? If for no other reason, doing so would be ill-advised because it would unnecessarily constrain implementations which would otherwise naturally represent null pointers by special, nonzero

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

bit patterns, particularly when those values would trigger automatic hardware traps for invalid accesses. Besides, what would such a requirement really accomplish? Proper understanding of null pointers does not require knowledge of the internal representation, whether zero or nonzero. Assuming that null pointers are internally zero does not make any code easier to write (except for a certain ill-advised usage of calloc(); see question 7.31). Known-zero internal pointers would not obviate casts in function calls, because the *size* of the pointer might still be different from that of an int. (If "nil" were used to request null pointers, as mentioned in question 5.14 above, the urge to assume an internal zero representation would not even arise.) 5.17: Seriously, have any actual machines really used nonzero null pointers, or different representations for pointers to different types? The Prime 50 series used segment 07777, offset 0 for the null pointer, at least for PL/I. Later models used segment 0, offset 0 for null pointers in C, necessitating new instructions such as TCNP (Test C Null Pointer), evidently as a sop to all the extant poorly-written C code which made incorrect assumptions. Older, word-addressed Prime machines were also notorious for requiring larger byte pointers (char *'s) than word pointers (int *'s). The Eclipse MV series from Data General has three architecturally supported pointer formats (word, byte, and bit pointers), two of which are used by C compilers: byte pointers for char * and void *, and word pointers for everything else. Some Honeywell-Bull mainframes use the bit pattern 06000 for (internal) null pointers. The CDC Cyber 180 Series has 48-bit pointers consisting of a ring, segment, and offset. Most users (in ring 11) have null pointers of 0xB00000000000. It was common on old CDC ones-

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

complement machines to use an all-one-bits word as a special flag for all kinds of data, including invalid addresses. The old HP 3000 series uses a different addressing scheme for byte addresses than for word addresses; like several of the machines above it therefore uses different representations for char * and void * pointers than for other pointers. The Symbolics Lisp Machine, a tagged architecture, does not even have conventional numeric pointers; it uses the pair <NIL, 0> (basically a nonexistent <object, offset> handle) as a C null pointer. Depending on the "memory model" in use, 8086-family processors (PC compatibles) may use 16-bit data pointers and 32-bit function pointers, or vice versa. Some 64-bit Cray machines represent int * in the lower 48 bits of a word; char * additionally uses the upper 16 bits to indicate a byte address within a word. References: K&R1 Sec. A14.4 p. 211. 5.20: What does a run-time "null pointer assignment" error mean? How can I track it down? This message, which typically occurs with MS-DOS compilers, means that you've written, via a null (perhaps because uninitialized) pointer, to an invalid location (probably offset 0 in the default data segment). A debugger may let you set a data watchpoint on location 0. Alternatively, you could write a bit of code to stash away a copy of 20 or so bytes from location 0, and periodically check that the memory at location 0 hasn't changed. See also question 16.8.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Section 6. Arrays and Pointers 6.1: I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn't it work? In one source file you defind an array of characters and in the other you declared a pointer to characters. The declaration extern char *a simply does not match the actual definition. The type pointer-to-type-T is not the same as array-of-type-T. Use extern char a[]. References: ISO Sec. 6.5.4.2; CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5. 6.2: A: But I heard that char a[] was identical to char *a. Not at all. (What you heard has to do with formal parameters to functions; see question 6.4.) Arrays are not pointers. The array declaration char a[6] requests that space for six characters be set aside, to be known by the name "a". That is, there is a location named "a" at which six characters can sit. The pointer declaration char *p, on the other hand, requests a place which holds a pointer, to be known by the name "p". This pointer can point almost anywhere: to any char, or to any contiguous array of chars, or nowhere (see also questions 5.1 and 1.30). As usual, a picture is worth a thousand words. char a[] = "hello"; char *p = "world"; would initialize data structures which could be represented like this: +---+---+---+---+---+---+ a: | h | e | l | l | o |\0 | +---+---+---+---+---+---+ +-----+ +---+---+---+---+---+---+ The declarations

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

p: | *======> | w | o | r | l | d |\0 | +-----+ +---+---+---+---+---+---+ It is important to realize that a reference like x[3] generates different code depending on whether x is an array or a pointer. Given the declarations above, when the compiler sees the expression a[3], it emits code to start at the location "a", move three past it, and fetch the character there. When it sees the expression p[3], it emits code to start at the location "p", fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to. In other words, a[3] is three places past (the start of) the object *named* a, while p[3] is three places past the object *pointed to* by p. In the example above, both a[3] and p[3] happen to be the character 'l', but the compiler gets there differently. (The essential difference is that the values of an array like a and a pointer like p are computed differently *whenever* they appear in expressions, whether or not they are being subscripted, as explained further in the next question.) References: K&R2 Sec. 5.5 p. 104; CT&P Sec. 4.5 pp. 64-5. 6.3: So what is meant by the "equivalence of pointers and arrays" in C? Much of the confusion surrounding arrays and pointers in C can be traced to a misunderstanding of this statement. Saying that arrays and pointers are "equivalent" means neither that they are identical nor even interchangeable. What it means is that array and pointer arithmetic is defined such that a pointer can be conveniently used to access an array or to simulate an array. Specifically, the cornerstone of the equivalence is this key definition: An lvalue of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

resultant pointer is pointer-to-T. That is, whenever an array appears in an expression, the compiler implicitly generates a pointer to the array's first element, just as if the programmer had written &a[0]. (The exceptions are when the array is the operand of a sizeof or & operator, or is a string literal initializer for a character array.) As a consequence of this definition, the compiler doesn't apply the array subscripting operator [] that differently to arrays and pointers, after all. In an expression of the form a[i], the array decays into a pointer, following the rule above, and is then subscripted just as would be a pointer variable in the expression p[i] (although the eventual memory accesses will be different, as explained in question 6.2). If you were to assign the array's address to the pointer: p = a; then p[3] and a[3] would access the same element. See also questions 6.8 and 6.14. References: K&R1 Sec. 5.3 pp. 93-6; K&R2 Sec. 5.3 p. 99; ISO Sec. 6.2.2.1, Sec. 6.3.2.1, Sec. 6.3.6; H&S Sec. 5.4.1 p. 124. 6.4: Then why are array and pointer declarations interchangeable as function formal parameters? It's supposed to be a convenience. Since arrays decay immediately into pointers, an array is never actually passed to a function. Allowing pointer parameters to be declared as arrays is a simply a way of making it look as though an array was being passed, perhaps because the parameter will be used within the function as if it were an array. Specifically, any parameter declarations which "look like"

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

arrays, e.g. void f(char a[]) { ... } are treated by the compiler as if they were pointers, since that is what the function will receive if an array is passed: void f(char *a) { ... } This conversion holds only within function formal parameter declarations, nowhere else. If the conversion bothers you, avoid it; many programmers have concluded that the confusion it causes outweighs the small advantage of having the declaration "look like" the call or the uses within the function. See also question 6.21. References: K&R1 Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R2 Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; ISO Sec. 6.5.4.3, Sec. 6.7.1, Sec. 6.9.6; H&S Sec. 9.3 p. 271; CT&P Sec. 3.3 pp. 33-4. 6.7: A: How can an array be an lvalue, if you can't assign to it? The ANSI C Standard defines a "modifiable lvalue," which an array is not. References: ISO Sec. 6.2.2.1; Rationale Sec. 3.2.2.1; H&S Sec. 7.1 p. 179. 6.8: Practically speaking, what is the difference between arrays and pointers? Arrays automatically allocate space, but can't be relocated or resized. Pointers must be explicitly assigned to point to allocated space (perhaps using malloc), but can be reassigned

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(i.e. pointed at different objects) at will, and have many other uses besides serving as the base of blocks of memory. Due to the so-called equivalence of arrays and pointers (see question 6.3), arrays and pointers often seem interchangeable, and in particular a pointer to a block of memory assigned by malloc is frequently treated (and can be referenced using []) exactly as if it were a true array. See questions 6.14 and 6.16. (Be careful with sizeof, though.) See also questions 1.32 and 20.14. 6.9: Someone explained to me that arrays were really just constant pointers. This is a bit of an oversimplification. An array name is "constant" in that it cannot be assigned to, but an array is *not* a pointer, as the discussion and pictures in question 6.2 should make clear. See also questions 6.3 and 6.8. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? Yes, Virginia, array subscripting is commutative in C. This curious fact follows from the pointer definition of array subscripting, namely that a[e] is identical to *((a)+(e)), for *any* two expressions a and e, as long as one of them is a pointer expression and one is integral. This unsuspected commutativity is often mentioned in C texts as if it were something to be proud of, but it finds no useful application outside of the Obfuscated C Contest (see question 20.36). References: Rationale Sec. 3.3.2.1; H&S Sec. 5.4.1 p. 124, Sec. 7.4.1 pp. 186-7. 6.12: Since array references decay into pointers, if arr is an array, what's the difference between arr and &arr?

A:

6.11:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

The type. In Standard C, &arr yields a pointer, of type pointer-to-arrayof-T, to the entire array. (In pre-ANSI C, the & in &arr generally elicited a warning, and was generally ignored.) Under all C compilers, a simple reference (without an explicit &) to an array yields a pointer, of type pointer-to-T, to the array's first element. (See also questions 6.3, 6.13, and 6.18.) References: ISO Sec. 6.2.2.1, Sec. 6.3.3.2; Rationale Sec. 3.3.3.2; H&S Sec. 7.5.6 p. 198.

6.13: A:

How do I declare a pointer to an array? Usually, you don't want to. When people speak casually of a pointer to an array, they usually mean a pointer to its first element. Instead of a pointer to an array, consider using a pointer to one of the array's elements. Arrays of type T decay into pointers to type T (see question 6.3), which is convenient; subscripting or incrementing the resultant pointer will access the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally useful only when operating on arrays of arrays, if at all. (See question 6.18.) If you really need to declare a pointer to an entire array, use something like "int (*ap)[N];" where N is the size of the array. (See also question 1.21.) If the size of the array is unknown, N can in principle be omitted, but the resulting type, "pointer to array of unknown size," is useless. See also question 6.12 above. References: ISO Sec. 6.2.2.1.

6.14:

How can I set an array's size at run time?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

How can I avoid fixed-sized arrays? A: The equivalence between arrays and pointers (see question 6.3) allows a pointer to malloc'ed memory to simulate an array quite effectively. After executing #include <stdlib.h> int *dynarray; dynarray = malloc(10 * sizeof(int)); (and if the call to malloc succeeds), you can reference dynarray[i] (for i from 0 to 9) almost as if dynarray were a conventional, statically-allocated array (int a[10]). The only difference is that sizeof will not give the size of the "array". See also questions 1.31b, 6.16, and 7.7. 6.15: How can I declare local arrays of a size matching a passed-in array? Until recently, you couldn't. Array dimensions in C traditionally had to be compile-time constants. C9X will introduce variable-length arrays (VLA's) which will solve this problem; local arrays may have sizes set by variables or other expressions, perhaps involving function parameters. (gcc has provided parameterized arrays as an extension for some time.) If you can't use C9X or gcc, you'll have to use malloc(), and remember to call free() before the function returns. See also questions 6.14, 6.16, 6.19, 7.22, and maybe 7.32. References: ISO Sec. 6.4, Sec. 6.5.4.2; C9X Sec. 6.5.5.2. 6.16: A: How can I dynamically allocate a multidimensional array? The traditional solution is to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." Here is a two-dimensional example: #include <stdlib.h>

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

int **array1 = malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array1[i] = malloc(ncolumns * sizeof(int)); (In real code, of course, all of malloc's return values would be checked.) You can keep the array's contents contiguous, at the cost of making later reallocation of individual rows more difficult, with a bit of explicit pointer arithmetic: int **array2 = malloc(nrows * sizeof(int *)); array2[0] = malloc(nrows * ncolumns * sizeof(int)); for(i = 1; i < nrows; i++) array2[i] = array2[0] + i * ncolumns; In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: arrayx[i][j] (for 0 <= i < nrows and 0 <= j < ncolumns). If the double indirection implied by the above schemes is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array: int *array3 = malloc(nrows * ncolumns * sizeof(int)); However, you must now perform subscript calculations manually, accessing the i,jth element with array3[i * ncolumns + j]. (A macro could hide the explicit calculation, but invoking it would require parentheses and commas which wouldn't look exactly like multidimensional array syntax, and the macro would need access to at least one of the dimensions, as well. See also question 6.19.) Yet another option is to use pointers to arrays:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

int (*array4)[NCOLUMNS] = malloc(nrows * sizeof(*array4)); but the syntax starts getting horrific and at most one dimension may be specified at run time. With all of these techniques, you may of course need to remember to free the arrays (which may take several steps; see question 7.23) when they are no longer needed, and you cannot necessarily intermix dynamically-allocated arrays with conventional, statically-allocated ones (see question 6.20, and also question 6.18). Finally, in C9X you can use a variable-length array. All of these techniques can also be extended to three or more dimensions. References: C9X Sec. 6.5.5.2. 6.17: Here's a neat trick: if I write int realarray[10]; int *array = &realarray[-1]; I can treat "array" as if it were a 1-based array. A: Although this technique is attractive (and was used in old editions of the book _Numerical Recipes in C_), it is not strictly conforming to the C Standard. Pointer arithmetic is defined only as long as the pointer points within the same allocated block of memory, or to the imaginary "terminating" element one past it; otherwise, the behavior is undefined, *even if the pointer is not dereferenced*. The code above could fail if, while subtracting the offset, an illegal address were generated (perhaps because the address tried to "wrap around" past the beginning of some memory segment). References: K&R2 Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

pp. 205-6; ISO Sec. 6.3.6; Rationale Sec. 3.2.2.3. 6.18: My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer. The rule (see question 6.3) by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a twodimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays can be confusing, and must be treated carefully; see also question 6.13. If you are passing a two-dimensional array to a function: int array[NROWS][NCOLUMNS]; f(array); the function's declaration must match: void f(int a[][NCOLUMNS]) { ... } or void f(int (*ap)[NCOLUMNS]) { ... } /* ap is a pointer to an array */

A:

In the first declaration, the compiler performs the usual implicit parameter rewriting of "array of array" to "pointer to array" (see questions 6.3 and 6.4); in the second form the pointer declaration is explicit. Since the called function does not allocate space for the array, it does not need to know the overall size, so the number of rows, NROWS, can be omitted. The width of the array is still important, so the column dimension NCOLUMNS (and, for three- or more dimensional arrays, the intervening ones) must be retained. If a function is already declared as accepting a pointer to a pointer, it is almost certainly meaningless to pass a two-

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

dimensional array directly to it. See also questions 6.12 and 6.15. References: K&R1 Sec. 5.10 p. 110; K&R2 Sec. 5.9 p. 113; H&S Sec. 5.4.3 p. 126. 6.19: How do I write functions which accept two-dimensional arrays when the width is not known at compile time? It's not always easy. One way is to pass in a pointer to the [0][0] element, along with the two dimensions, and simulate array subscripting "by hand": void f2(int *aryp, int nrows, int ncolumns) { ... array[i][j] is accessed as aryp[i * ncolumns + j] ... } This function could be called with the array from question 6.18 as f2(&array[0][0], NROWS, NCOLUMNS); It must be noted, however, that a program which performs multidimensional array subscripting "by hand" in this way is not in strict conformance with the ANSI C Standard; according to an official interpretation, the behavior of accessing (&array[0][0])[x] is not defined for x >= NCOLUMNS. C9X will allow variable-length arrays, and once compilers which accept C9X's extensions become widespread, this will probably become the preferred solution. (gcc has supported variablesized arrays for some time.) When you want to be able to use a function on multidimensional arrays of various sizes, one solution is to simulate all the arrays dynamically, as in question 6.16. See also questions 6.18, 6.20, and 6.15.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: ISO Sec. 6.3.6; C9X Sec. 6.5.5.2. 6.20: How can I use statically- and dynamically-allocated multidimensional arrays interchangeably when passing them to functions? There is no single perfect method. int int int int int array[NROWS][NCOLUMNS]; **array1; **array2; *array3; (*array4)[NCOLUMNS]; Given the declarations

A:

/* ragged */ /* contiguous */ /* "flattened" */

with the pointers initialized as in the code fragments in question 6.16, and functions declared as void void void void f1a(int a[][NCOLUMNS], int nrows, int ncolumns); f1b(int (*a)[NCOLUMNS], int nrows, int ncolumns); f2(int *aryp, int nrows, int ncolumns); f3(int **pp, int nrows, int ncolumns);

where f1a() and f1b() accept conventional two-dimensional arrays, f2() accepts a "flattened" two-dimensional array, and f3() accepts a pointer-to-pointer, simulated array (see also questions 6.18 and 6.19), the following calls should work as expected: f1a(array, NROWS, NCOLUMNS); f1b(array, NROWS, NCOLUMNS); f1a(array4, nrows, NCOLUMNS); f1b(array4, nrows, NCOLUMNS); f2(&array[0][0], NROWS, NCOLUMNS); f2(*array, NROWS, NCOLUMNS); f2(*array2, nrows, ncolumns); f2(array3, nrows, ncolumns); f2(*array4, nrows, NCOLUMNS);

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

f3(array1, nrows, ncolumns); f3(array2, nrows, ncolumns); The following calls would probably work on most systems, but involve questionable casts, and work only if the dynamic ncolumns matches the static NCOLUMNS: f1a((int f1a((int f1b((int f1b((int (*)[NCOLUMNS])(*array2), nrows, ncolumns); (*)[NCOLUMNS])(*array2), nrows, ncolumns); (*)[NCOLUMNS])array3, nrows, ncolumns); (*)[NCOLUMNS])array3, nrows, ncolumns);

It must again be noted that passing &array[0][0] (or, equivalently, *array) to f2() is not strictly conforming; see question 6.19. If you can understand why all of the above calls work and are written as they are, and if you understand why the combinations that are not listed would not work, then you have a *very* good understanding of arrays and pointers in C. Rather than worrying about all of this, one approach to using multidimensional arrays of various sizes is to make them *all* dynamic, as in question 6.16. If there are no static multidimensional arrays -- if all arrays are allocated like array1 or array2 in question 6.16 -- then all functions can be written like f3(). 6.21: Why doesn't sizeof properly report the size of an array when the array is a parameter to a function? The compiler pretends that the array parameter was declared as a pointer (see question 6.4), and sizeof reports the size of the pointer. References: H&S Sec. 7.5.2 p. 195.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Section 7. Memory Allocation 7.1: Why doesn't this fragment work? char *answer; printf("Type something:\n"); gets(answer); printf("You typed \"%s\"\n", answer); A: The pointer variable answer, which is handed to gets() as the location into which the response should be stored, has not been set to point to any valid storage. That is, we cannot say where the pointer answer points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that answer starts out as a null pointer. See questions 1.30 and 5.1.) The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation: #include <stdio.h> #include <string.h> char answer[100], *p; printf("Type something:\n"); fgets(answer, sizeof answer, stdin); if((p = strchr(answer, '\n')) != NULL) *p = '\0'; printf("You typed \"%s\"\n", answer); This example also uses fgets() instead of gets(), so that the end of the array cannot be overwritten. (See question 12.23. Unfortunately for this example, fgets() does not automatically delete the trailing \n, as gets() would.) It would also be possible to use malloc() to allocate the answer buffer. 7.2: I can't get strcat() to work. I tried

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

char *s1 = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); but I got strange results. A: As in question 7.1 above, the main problem here is that space for the concatenated result is not properly allocated. C does not provide an automatically-managed string type. C compilers only allocate memory for objects explicitly mentioned in the source code (in the case of strings, this includes character arrays and string literals). The programmer must arrange for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or by calling malloc(). strcat() performs no allocation; the second string is appended to the first one, in place. Therefore, one fix would be to declare the first string as an array: char s1[20] = "Hello, "; Since strcat() returns the value of its first argument (s1, in this case), the variable s3 is superfluous; after the call to strcat(), s1 contains the result. The original call to strcat() in the question actually has two problems: the string literal pointed to by s1, besides not being big enough for any concatenated text, is not necessarily writable at all. See question 1.32. References: CT&P Sec. 3.2 p. 32. 7.3: But the man page for strcat() says that it takes two char *'s as arguments. How am I supposed to know to allocate things? In general, when using pointers you *always* have to consider

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

memory allocation, if only to make sure that the compiler is doing it for you. If a library function's documentation does not explicitly mention allocation, it is usually the caller's problem. The Synopsis section at the top of a Unix-style man page or in the ANSI C standard can be misleading. The code fragments presented there are closer to the function definitions used by an implementor than the invocations used by the caller. In particular, many functions which accept pointers (e.g. to structures or strings) are usually called with a pointer to some object (a structure, or an array -- see questions 6.3 and 6.4) which the caller has allocated. Other common examples are time() (see question 13.12) and stat(). 7.3b: I just tried the code char *p; strcpy(p, "abc"); and it worked. A: How? Why didn't it crash?

You got lucky, I guess. The memory pointed to by the unitialized pointer p happened to be writable by you, and apparently was not already in use for anything vital. How much memory does a pointer variable allocate? That's a pretty misleading question. a pointer variable, as in char *p; you (or, more properly, the compiler) have allocated only enough memory to hold the pointer itself; that is, in this case you have allocated sizeof(char *) bytes of memory. But you have not yet allocated *any* memory for the pointer to point to. See also questions 7.1 and 7.2. When you declare

7.3c: A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

7.5a:

I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage. Make sure that the pointed-to memory is properly allocated. For example, make sure you have *not* done something like char *itoa(int n) { char retbuf[20]; sprintf(retbuf, "%d", n); return retbuf; }

A:

/* WRONG */ /* WRONG */

One fix (which is imperfect, especially if the function in question is called recursively, or if several of its return values are needed simultaneously) would be to declare the return buffer as static char retbuf[20]; See also questions 7.5b, 12.21, and 20.1. References: ISO Sec. 6.1.2.4. 7.5b: A: So what's the right way to return a string or other aggregate? The returned pointer should be to a statically-allocated buffer, or to a buffer passed in by the caller, or to memory obtained with malloc(), but *not* to a local (automatic) array. See also question 20.1. 7.6: Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to malloc()? Have you #included <stdlib.h>, or otherwise arranged for malloc() to be declared properly? See also question 1.25.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: H&S Sec. 4.7 p. 101. 7.7: Why does some code carefully cast the values returned by malloc to the pointer type being allocated? Before ANSI/ISO Standard C introduced the void * generic pointer type, these casts were typically required to silence warnings (and perhaps induce conversions) when assigning between incompatible pointer types. Under ANSI/ISO Standard C, these casts are no longer necessary, and in fact modern practice discourages them, since they can camouflage important warnings which would otherwise be generated if malloc() happened not to be declared correctly; see question 7.6 above. (However, the casts are typically seen in C code which for one reason or another is intended to be compatible with C++, where explicit casts from void * are required.) References: H&S Sec. 16.1 pp. 386-7. 7.8: I see code like char *p = malloc(strlen(s) + 1); strcpy(p, s); Shouldn't that be malloc((strlen(s) + 1) * sizeof(char))? A: It's never necessary to multiply by sizeof(char), since sizeof(char) is, by definition, exactly 1. (On the other hand, multiplying by sizeof(char) doesn't hurt, and in some circumstances may help by introducing a size_t into the expression.) See also question 8.9. References: ISO Sec. 6.3.3.4; H&S Sec. 7.5.2 p. 195. 7.14: I've heard that some operating systems don't actually allocate malloc'ed memory until the program tries to use it. Is this

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

legal? A: It's hard to say. The Standard doesn't say that systems can act this way, but it doesn't explicitly say that they can't, either. References: ISO Sec. 7.10.3. 7.16: I'm allocating a large array for some numeric work, using the line double *array = malloc(300 * 300 * sizeof(double)); malloc() isn't returning null, but the program is acting strangely, as if it's overwriting memory, or malloc() isn't allocating as much as I asked for, or something. A: Notice that 300 x 300 is 90,000, which will not fit in a 16-bit int, even before you multiply it by sizeof(double). If you need to allocate this much memory, you'll have to be careful. If size_t (the type accepted by malloc()) is a 32-bit type on your machine, but int is 16 bits, you might be able to get away with writing 300 * (300 * sizeof(double)) (see question 3.14). Otherwise, you'll have to break your data structure up into smaller chunks, or use a 32-bit machine or compiler, or use some nonstandard memory allocation functions. See also question 19.23. I've got 8 meg of memory in my PC. malloc 640K or so? Why can I only seem to

7.17:

A:

Under the segmented architecture of PC compatibles, it can be difficult to use more than 640K with any degree of transparency, especially under MS-DOS. See also question 19.23. My program is crashing, apparently somewhere down inside malloc, but I can't see anything wrong with it. Is there a bug in malloc()?

7.19:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

It is unfortunately very easy to corrupt malloc's internal data structures, and the resulting problems can be stubborn. The most common source of problems is writing more to a malloc'ed region than it was allocated to hold; a particularly common bug is to malloc(strlen(s)) instead of strlen(s) + 1. Other problems may involve using pointers to memory that has been freed, freeing pointers twice, freeing pointers not obtained from malloc, or trying to realloc a null pointer (see question 7.30). See also questions 7.26, 16.8, and 18.2.

7.20:

You can't use dynamically-allocated memory after you free it, can you? No. Some early documentation for malloc() stated that the contents of freed memory were "left undisturbed," but this illadvised guarantee was never universal and is not required by the C Standard. Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list: struct list *listp, *nextp; for(listp = base; listp != NULL; listp = nextp) { nextp = listp->next; free(listp); } and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer. References: K&R2 Sec. 7.8.5 p. 167; ISO Sec. 7.10.3; Rationale Sec. 4.10.3.2; H&S Sec. 16.2 p. 387; CT&P Sec. 7.10 p. 95.

A:

7.21:

Why isn't a pointer null after calling free()?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

How unsafe is it to use (assign, compare) a pointer value after it's been freed? A: When you call free(), the memory pointed to by the passed pointer is freed, but the value of the pointer in the caller probably remains unchanged, because C's pass-by-value semantics mean that called functions never permanently change the values of their arguments. (See also question 4.8.) A pointer value which has been freed is, strictly speaking, invalid, and *any* use of it, even if is not dereferenced, can theoretically lead to trouble, though as a quality of implementation issue, most implementations will probably not go out of their way to generate exceptions for innocuous uses of invalid pointers. References: ISO Sec. 7.10.3; Rationale Sec. 3.2.2.3. 7.22: When I call malloc() to allocate memory for a pointer which is local to a function, do I have to explicitly free() it? Yes. Remember that a pointer is different from what it points to. Local variables are deallocated when the function returns, but in the case of a pointer variable, this means that the pointer is deallocated, *not* what it points to. Memory allocated with malloc() always persists until you explicitly free it. In general, for every call to malloc(), there should be a corresponding call to free(). I'm allocating structures which contain pointers to other dynamically-allocated objects. When I free a structure, do I also have to free each subsidiary pointer? Yes. In general, you must arrange that each pointer returned from malloc() be individually passed to free(), exactly once (if it is freed at all). A good rule of thumb is that for each call to malloc() in a program, you should be able to point at the call to free() which frees the memory allocated by that malloc()

A:

7.23:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

call. See also question 7.24. 7.24: A: Must I free allocated memory before the program exits? You shouldn't have to. A real operating system definitively reclaims all memory and other resources when a program exits. Nevertheless, some personal computers are said not to reliably recover memory, and all that can be inferred from the ANSI/ISO C Standard is that this is a "quality of implementation issue." References: ISO Sec. 7.10.3.2. 7.25: I have a program which mallocs and later frees a lot of memory, but I can see from the operating system that memory usage doesn't actually go back down. Most implementations of malloc/free do not return freed memory to the operating system, but merely make it available for future malloc() calls within the same program. How does free() know how many bytes to free? The malloc/free implementation remembers the size of each block as it is allocated, so it is not necessary to remind it of the size when freeing. So can I query the malloc package to find out how big an allocated block is? Unfortunately, there is no standard or portable way. Is it legal to pass a null pointer as the first argument to realloc()? Why would you want to? ANSI C sanctions this usage (and the related realloc(..., 0), which frees), although several earlier implementations do not

A:

7.26: A:

7.27:

A: 7.30:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

support it, so it may not be fully portable. Passing an initially-null pointer to realloc() can make it easier to write a self-starting incremental allocation algorithm. References: ISO Sec. 7.10.3.4; H&S Sec. 16.3 p. 388. 7.31: What's the difference between calloc() and malloc()? Is it safe to take advantage of calloc's zero-filling? Does free() work on memory allocated with calloc(), or do you need a cfree()? calloc(m, n) is essentially equivalent to p = malloc(m * n); memset(p, 0, m * n); The zero fill is all-bits-zero, and does *not* therefore guarantee useful null pointer values (see section 5 of this list) or floating-point zero values. free() is properly used to free the memory allocated by calloc(). References: ISO Sec. 7.10.3 to 7.10.3.2; H&S Sec. 16.1 p. 386, Sec. 16.2 p. 386; PCS Sec. 11 pp. 141,142. 7.32: A: What is alloca() and why is its use discouraged? alloca() allocates memory which is automatically freed when the function which called alloca() returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context. alloca() cannot be written portably, and is difficult to implement on machines without a conventional stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), 100, stdin). For these reasons, alloca() is not Standard and cannot be used in programs which must be widely portable, no matter how useful

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

it might be. See also question 7.22. References: Rationale Sec. 4.10.3.

Section 8. Characters and Strings 8.1: Why doesn't strcat(string, '!'); work? A: There is a very real difference between characters and strings, and strcat() concatenates *strings*. Characters in C are represented by small integers corresponding to their character set values (see also question 8.6 below). Strings are represented by arrays of characters; you usually manipulate a pointer to the first character of the array. It is never correct to use one when the other is expected. To append a ! to a string, use strcat(string, "!"); See also questions 1.32, 7.2, and 16.6. References: CT&P Sec. 1.5 pp. 9-10. 8.2: I'm checking a string to see if it matches a particular value. Why isn't this code working? char *string; ... if(string == "value") { /* string matches "value" */

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

... } A: Strings in C are represented as arrays of characters, and C never manipulates (assigns, compares, etc.) arrays as a whole. The == operator in the code fragment above compares two pointers -- the value of the pointer variable string and a pointer to the string literal "value" -- to see if they are equal, that is, if they point to the same place. They probably don't, so the comparison never succeeds. To compare two strings, you generally use the library function strcmp(): if(strcmp(string, "value") == 0) { /* string matches "value" */ ... } 8.3: If I can say char a[] = "Hello, world!"; why can't I say char a[14]; a = "Hello, world!"; A: Strings are arrays, and you can't assign arrays directly. strcpy() instead: strcpy(a, "Hello, world!"); See also questions 1.32, 4.2, and 7.2. 8.6: How can I get the numeric (character set) value corresponding to a character, or vice versa? Use

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

In C, characters are represented by small integers corresponding to their values (in the machine's character set), so you don't need a conversion function: if you have the character, you have its value. I think something's wrong with my compiler: I just noticed that sizeof('a') is 2, not 1 (i.e. not sizeof(char)). Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs). See also question 7.8. References: ISO Sec. 6.1.3.4; H&S Sec. 2.7.3 p. 29.

8.9:

A:

Section 9. Boolean Expressions and Variables 9.1: What is the right type to use for Boolean values in C? Why isn't it a standard type? Should I use #defines or enums for the true and false values? C does not provide a standard Boolean type, in part because picking one involves a space/time tradeoff which can best be decided by the programmer. (Using an int may be faster, while using char may save data space. Smaller types may make the generated code bigger or slower, though, if they require lots of conversions to and from int.) The choice between #defines and enumeration constants for the true/false values is arbitrary and not terribly interesting (see also questions 2.22 and 17.10). Use any of #define TRUE 1 #define FALSE 0 enum bool {false, true}; #define YES 1 #define NO 0 enum bool {no, yes};

A:

or use raw 1 and 0, as long as you are consistent within one

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

program or project. (An enumeration may be preferable if your debugger shows the names of enumeration constants when examining variables.) Some people prefer variants like #define TRUE (1==1) #define FALSE (!TRUE) or define "helper" macros such as #define Istrue(e) ((e) != 0) These don't buy anything (see question 9.2 below; see also questions 5.12 and 10.2). 9.2: Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in logical or relational operator "returns" something other than 1? It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a Boolean value is expected. When a Boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test if((a == b) == TRUE) would work as expected (as long as TRUE is 1), but it is obviously silly. In fact, explicit tests against TRUE and FALSE are generally inappropriate, because some library functions (notably isupper(), isalpha(), etc.) return, on success, a nonzero value which is not necessarily 1. (Besides, if you believe that "if((a == b) == TRUE)" is an improvement over "if(a == b)", why stop there? Why not use "if(((a == b) == TRUE) == TRUE)"?) A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable or function parameter, or as the return value from a Boolean function, but never in a comparison.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The preprocessor macros TRUE and FALSE (and, of course, NULL) are used for code readability, not because the underlying values might ever change. (See also questions 5.3 and 5.10.) Although the use of macros like TRUE and FALSE (or YES and NO) seems clearer, Boolean values and definitions can be sufficiently confusing in C that some programmers feel that TRUE and FALSE macros only compound the confusion, and prefer to use raw 1 and 0 instead. (See also question 5.9.) References: K&R1 Sec. 2.6 p. 39, Sec. 2.7 p. 41; K&R2 Sec. 2.6 p. 42, Sec. 2.7 p. 44, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ISO Sec. 6.3.3.3, Sec. 6.3.8, Sec. 6.3.9, Sec. 6.3.13, Sec. 6.3.14, Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5; H&S Sec. 7.5.4 pp. 196-7, Sec. 7.6.4 pp. 207-8, Sec. 7.6.5 pp. 208-9, Sec. 7.7 pp. 217-8, Sec. 7.8 pp. 218-9, Sec. 8.5 pp. 238-9, Sec. 8.6 pp. 241-4; "What the Tortoise Said to Achilles". 9.3: A: Is if(p), where p is a pointer, a valid conditional? Yes. See question 5.3.

Section 10. C Preprocessor 10.2: Here are some cute preprocessor macros: #define begin #define end What do y'all think? A: 10.3: A: Bleah. See also section 17. { }

How can I write a generic macro to swap two values? There is no good answer to this question. If the values are

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers, or if the two values are the same variable. (See questions 3.3b and 20.15c.) If the macro is intended to be used on values of arbitrary type (the usual goal), it cannot use a temporary, since it does not know what type of temporary it needs (and would have a hard time picking a name for it if it did), and standard C does not provide a typeof operator. The best all-around solution is probably to forget about using a macro, unless you're willing to pass in the type as a third argument. 10.4: A: What's the best way to write a multi-statement macro? The usual goal is to write a macro that can be invoked as if it were a statement consisting of a single function call. This means that the "caller" will be supplying the final semicolon, so the macro body should not. The macro body cannot therefore be a simple brace-enclosed compound statement, because syntax errors would result if it were invoked (apparently as a single statement, but with a resultant extra semicolon) as the if branch of an if/else statement with an explicit else clause. The traditional solution, therefore, is to use #define MACRO(arg1, arg2) do { \ /* declarations */ \ stmt1; \ stmt2; \ /* ... */ \ } while(0) /* (no trailing ; ) */ When the caller appends a semicolon, this expansion becomes a single statement regardless of context. (An optimizing compiler will remove any "dead" tests or branches on the constant condition 0, although lint may complain.)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

If all of the statements in the intended macro are simple expressions, with no declarations or loops, another technique is to write a single, parenthesized expression using one or more comma operators. (For an example, see the first DEBUG() macro in question 10.26.) This technique also allows a value to be "returned." References: H&S Sec. 3.3.2 p. 45; CT&P Sec. 6.3 pp. 82-3. 10.6: I'm splitting up a program into multiple source files for the first time, and I'm wondering what to put in .c files and what to put in .h files. (What does ".h" mean, anyway?) As a general rule, you should put these things in header (.h) files: macro definitions (preprocessor #defines) structure, union, and enumeration declarations typedef declarations external function declarations (see also question 1.11) global variable declarations It's especially important to put a declaration or definition in a header file when it will be shared between several other files. (In particular, never put external function prototypes in .c files. See also question 1.7.) On the other hand, when a definition or declaration should remain private to one .c file, it's fine to leave it there. See also questions 1.7 and 10.7. References: K&R2 Sec. 4.5 pp. 81-2; H&S Sec. 9.2.3 p. 267; CT&P Sec. 4.6 pp. 66-7. 10.7: A: Is it acceptable for one header file to #include another? It's a question of style, and thus receives considerable debate.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Many people believe that "nested #include files" are to be avoided: the prestigious Indian Hill Style Guide (see question 17.9) disparages them; they can make it harder to find relevant definitions; they can lead to multiple-definition errors if a file is #included twice; and they make manual Makefile maintenance very difficult. On the other hand, they make it possible to use header files in a modular way (a header file can #include what it needs itself, rather than requiring each #includer to do so); a tool like grep (or a tags file) makes it easy to find definitions no matter where they are; a popular trick along the lines of: #ifndef HFILENAME_USED #define HFILENAME_USED ...header file contents... #endif (where a different bracketing macro name is used for each header file) makes a header file "idempotent" so that it can safely be #included multiple times; and automated Makefile maintenance tools (which are a virtual necessity in large projects anyway; see question 18.1) handle dependency generation in the face of nested #include files easily. See also question 17.10. References: Rationale Sec. 4.1.2. 10.8a: What's the difference between #include <> and #include "" ? A: The <> syntax is typically used with Standard or system-supplied headers, while "" is typically used for a program's own header files.

10.8b: What are the complete rules for header file searching? A: The exact behavior is implementation-defined (which means that it is supposed to be documented; see question 11.33). Typically, headers named with <> syntax are searched for in one or more standard places. Header files named with "" syntax are

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

first searched for in the "current directory," then (if not found) in the same standard places. Traditionally (especially under Unix compilers), the current directory is taken to be the directory containing the file containing the #include directive. Under other compilers, however, the current directory (if any) is the directory in which the compiler was initially invoked. Check your compiler documentation. References: K&R2 Sec. A12.4 p. 231; ISO Sec. 6.8.2; H&S Sec. 3.4 p. 55. 10.9: I'm getting strange syntax errors on the very first declaration in a file, but it looks fine. Perhaps there's a missing semicolon at the end of the last declaration in the last header file you're #including. See also questions 2.18, 11.29, and 16.1b.

A:

10.10b: I'm #including the right header file for the library function I'm using, but the linker keeps saying it's undefined. A: See question 13.25.

10.11: I seem to be missing the system header file <sgtty.h>. Can someone send me a copy? A: Standard headers exist in part so that definitions appropriate to your compiler, operating system, and processor can be supplied. You cannot just pick up a copy of someone else's header file and expect it to work, unless that person is using exactly the same environment. Ask your compiler vendor why the file was not provided (or to send a replacement copy).

10.12: How can I construct preprocessor #if expressions which compare strings?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

You can't do it directly; preprocessor #if arithmetic uses only integers. An alternative is to #define several macros with symbolic names and distinct integer values, and implement conditionals on those. See also question 20.17. References: K&R2 Sec. 4.11.3 p. 91; ISO Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.

10.13: Does the sizeof operator work in preprocessor #if directives? A: No. Preprocessing happens during an earlier phase of compilation, before type names have been parsed. Instead of sizeof, consider using the predefined constants in ANSI's <limits.h>, if applicable, or perhaps a "configure" script. (Better yet, try to write code which is inherently insensitive to type sizes; see also question 1.1.) References: ISO Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p. 225. 10.14: Can I use an #ifdef in a #define line, to define something two different ways? A: No. You can't "run the preprocessor on itself," so to speak. What you can do is use one of two completely separate #define lines, depending on the #ifdef setting. References: ISO Sec. 6.8.3, Sec. 6.8.3.4; H&S Sec. 3.2 pp. 40-1. 10.15: Is there anything like an #ifdef for typedefs? A: Unfortunately, no. You may have to keep sets of preprocessor macros (e.g. MY_TYPE_DEFINED) recording whether certain typedefs have been declared. (See also question 10.13.) References: ISO Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

225. 10.16: How can I use a preprocessor #if expression to tell if a machine is big-endian or little-endian? A: You probably can't. (Preprocessor arithmetic uses only long integers, and there is no concept of addressing.) Are you sure you need to know the machine's endianness explicitly? Usually it's better to write code which doesn't care. See also question 20.9. References: ISO Sec. 6.8.1; H&S Sec. 7.11.1 p. 225. 10.18: I inherited some code which contains far too many #ifdef's for my taste. How can I preprocess the code to leave only one conditional compilation set, without running it through the preprocessor and expanding all of the #include's and #define's as well? A: There are programs floating around called unifdef, rmifdef, and scpp ("selective C preprocessor") which do exactly this. See question 18.16.

10.19: How can I list all of the predefined identifiers? A: There's no standard way, although it is a common need. gcc provides a -dM option which works with -E, and other compilers may provide something similar. If the compiler documentation is unhelpful, the most expedient way is probably to extract printable strings from the compiler or preprocessor executable with something like the Unix strings utility. Beware that many traditional system-specific predefined identifiers (e.g. "unix") are non-Standard (because they clash with the user's namespace) and are being removed or renamed.

10.20: I have some old code that tries to construct identifiers with a macro like

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#define Paste(a, b) a/**/b but it doesn't work any more. A: It was an undocumented feature of some early preprocessor implementations (notably John Reiser's) that comments disappeared entirely and could therefore be used for token pasting. ANSI affirms (as did K&R1) that comments are replaced with white space. However, since the need for pasting tokens was demonstrated and real, ANSI introduced a well-defined tokenpasting operator, ##, which can be used like this: #define Paste(a, b) a##b See also question 11.17. References: ISO Sec. 6.8.3.3; Rationale Sec. 3.8.3.3; H&S Sec. 3.3.9 p. 52. 10.22: Why is the macro #define TRACE(n) printf("TRACE: %d\n", n) giving me the warning "macro replacement within a string literal"? It seems to be expanding TRACE(count); as printf("TRACE: %d\count", count); A: See question 11.18.

10.23-4: I'm having trouble using macro arguments inside string literals, using the `#' operator. A: See questions 11.17 and 11.18.

10.25: I've got this tricky preprocessing I want to do and I can't

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

figure out a way to do it. A: C's preprocessor is not intended as a general-purpose tool. (Note also that it is not guaranteed to be available as a separate program.) Rather than forcing it to do something inappropriate, consider writing your own little special-purpose preprocessing tool, instead. You can easily get a utility like make(1) to run it for you automatically. If you are trying to preprocess something other than C, consider using a general-purpose preprocessor. (One older one available on most Unix systems is m4.) 10.26: How can I write a macro which takes a variable number of arguments? A: One popular trick is to define and invoke the macro with a single, parenthesized "argument" which in the macro expansion becomes the entire argument list, parentheses and all, for a function such as printf(): #define DEBUG(args) (printf("DEBUG: "), printf args) if(n != 0) DEBUG(("n is %d\n", n)); The obvious disadvantage is that the caller must always remember to use the extra parentheses. gcc has an extension which allows a function-like macro to accept a variable number of arguments, but it's not standard. Other possible solutions are to use different macros (DEBUG1, DEBUG2, etc.) depending on the number of arguments, or to play tricky games with commas: #define DEBUG(args) (printf("DEBUG: "), printf(args)) #define _ , DEBUG("i = %d" _ i)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

C9X will introduce formal support for function-like macros with variable-length argument lists. The notation ... will appear at the end of the macro "prototype" (just as it does for varargs functions), and the pseudomacro __VA_ARGS__ in the macro definition will be replaced by the variable arguments during invocation. Finally, you can always use a bona-fide function, which can take a variable number of arguments in a well-defined way. See questions 15.4 and 15.5. (If you needed a macro replacement, try using a function plus a non-function-like macro, e.g. #define printf myprintf .) References: C9X Sec. 6.8.3, Sec. 6.8.3.1.

Section 11. ANSI/ISO Standard C 11.1: A: What is the "ANSI C Standard?" In 1983, the American National Standards Institute (ANSI) commissioned a committee, X3J11, to standardize the C language. After a long, arduous process, including several widespread public reviews, the committee's work was finally ratified as ANS X3.159-1989 on December 14, 1989, and published in the spring of 1990. For the most part, ANSI C standardizes existing practice, with a few additions from C++ (most notably function prototypes) and support for multinational character sets (including the controversial trigraph sequences). The ANSI C standard also formalizes the C run-time library support routines. More recently, the Standard has been adopted as an international standard, ISO/IEC 9899:1990, and this ISO Standard replaces the earlier X3.159 even within the United States (where it is known as ANSI/ISO 9899-1990 [1992]). As an ISO Standard, it is subject to ongoing revision through the release of Technical Corrigenda and Normative Addenda.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

In 1994, Technical Corrigendum 1 (TC1) amended the Standard in about 40 places, most of them minor corrections or clarifications, and Normative Addendum 1 (NA1) added about 50 pages of new material, mostly specifying new library functions for internationalization. In 1995, TC2 added a few more minor corrections. As of this writing, a complete revision of the Standard is in its final stages. The new Standard is nicknamed "C9X" on the assumption that it will be finished by the end of 1999. (Many of this article's answers have been updated to reflect new C9X features.) The original ANSI Standard included a "Rationale," explaining many of its decisions, and discussing a number of subtle points, including several of those covered here. (The Rationale was "not part of ANSI Standard X3.159-1989, but... included for information only," and is not included with the ISO Standard. A new one is being prepared for C9X.) 11.2: A: How can I get a copy of the Standard? Copies are available in the United States from American National Standards Institute 11 W. 42nd St., 13th floor New York, NY 10036 USA (+1) 212 642 4900 and Global Engineering Documents 15 Inverness Way E Englewood, CO 80112 USA (+1) 303 397 2715 (800) 854 7179 (U.S. & Canada)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

In other countries, contact the appropriate national standards body, or ISO in Geneva at: ISO Sales Case Postale 56 CH-1211 Geneve 20 Switzerland (or see URL http://www.iso.ch/ or check the comp.std.internat FAQ list, Standards.Faq). The last time I checked, the cost was $130.00 from ANSI or $400.50 from Global. Copies of the original X3.159 (including the Rationale) may still be available at $205.00 from ANSI or $162.50 from Global. Note that ANSI derives revenues to support its operations from the sale of printed standards, so electronic copies are *not* available. In the U.S., it may be possible to get a copy of the original ANSI X3.159 (including the Rationale) as "FIPS PUB 160" from National Technical Information Service (NTIS) U.S. Department of Commerce Springfield, VA 22161 703 487 4650 The mistitled _Annotated ANSI C Standard_, with annotations by Herbert Schildt, contains most of the text of ISO 9899; it is published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells in the U.S. for approximately $40. It has been suggested that the price differential between this work and the official standard reflects the value of the annotations: they are plagued by numerous errors and omissions, and a few pages of the Standard itself are missing. Many people on the net recommend ignoring the annotations entirely. A review of the annotations ("annotated annotations") by Clive Feather can be found on the web at http://www.lysator.liu.se/c/schildt.html .

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The text of the Rationale (not the full Standard) can be obtained by anonymous ftp from ftp.uu.net (see question 18.16) in directory doc/standards/ansi/X3.159-1989, and is also available on the web at http://www.lysator.liu.se/c/rat/title.html . The Rationale has also been printed by Silicon Press, ISBN 0-929306-07-4. Public review drafts of C9X are available from ISO/IEC JTC1/SC22/WG14's web site, http://www.dkuug.dk/JTC1/SC22/WG14/ . See also question 11.2b below. 11.2b: Where can I get information about updates to the Standard? A: You can find information (including C9X drafts) at the web sites http://www.lysator.liu.se/c/index.html, http://www.dkuug.dk/JTC1/SC22/WG14/, and http://www.dmk.com/ . My ANSI compiler complains about a mismatch when it sees extern int func(float); int func(x) float x; { ... A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". It is usually possible to mix the two styles (see question 11.4), but not in this case. Old C (and ANSI C, in the absence of prototypes, and in variablelength argument lists; see question 15.2) "widens" certain arguments when they are passed to functions. floats are promoted to double, and characters and short integers are promoted to int. (For old-style function definitions, the values are automatically converted back to the corresponding narrower types within the body of the called function, if they

11.3:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

are declared that way there.) This problem can be fixed either by using new-style syntax consistently in the definition: int func(float x) { ... } or by changing the new-style prototype declaration to match the old-style definition: extern int func(double); (In this case, it would be clearest to change the old-style definition to use double as well, if possible.) It is arguably much safer to avoid "narrow" (char, short int, and float) function arguments and return types altogether. See also question 1.25. References: K&R1 Sec. A7.1 p. 186; K&R2 Sec. A7.3.2 p. 202; ISO Sec. 6.3.2.2, Sec. 6.5.4.3; Rationale Sec. 3.3.2.2, Sec. 3.5.4.3; H&S Sec. 9.2 pp. 265-7, Sec. 9.4 pp. 272-3. 11.4: A: Can you mix old-style and new-style function syntax? Doing so is legal, but requires a certain amount of care (see especially question 11.3). Modern practice, however, is to use the prototyped form in both declarations and definitions. (The old-style syntax is marked as obsolescent, so official support for it may be removed some day.) References: ISO Sec. 6.7.1, Sec. 6.9.5; H&S Sec. 9.2.2 pp. 2657, Sec. 9.2.5 pp. 269-70. 11.5: Why does the declaration extern int f(struct x *p);

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

give me an obscure warning message about "struct x introduced in prototype scope"? A: In a quirk of C's normal block scoping rules, a structure declared (or even mentioned) for the first time within a prototype cannot be compatible with other structures declared in the same source file (it goes out of scope at the end of the prototype). To resolve the problem, precede the prototype with the vacuouslooking declaration struct x; which places an (incomplete) declaration of struct x at file scope, so that all following declarations involving struct x can at least be sure they're referring to the same struct x. References: ISO Sec. 6.1.2.1, Sec. 6.1.2.6, Sec. 6.5.2.3. 11.8: I don't understand why I can't use const values in initializers and array dimensions, as in const int n = 5; int a[n]; A: The const qualifier really means "read-only"; an object so qualified is a run-time object which cannot (normally) be assigned to. The value of a const-qualified object is therefore *not* a constant expression in the full sense of the term. (C is unlike C++ in this regard.) When you need a true compiletime constant, use a preprocessor #define (or perhaps an enum). References: ISO Sec. 6.4; H&S Secs. 7.11.2,7.11.3 pp. 226-7. 11.9: What's the difference between "const char *p" and "char * const p"?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

"const char *p" (which can also be written "char const *p") declares a pointer to a constant character (you can't change the character); "char * const p" declares a constant pointer to a (variable) character (i.e. you can't change the pointer). Read these "inside out" to understand them; see also question 1.21. References: ISO Sec. 6.5.4.1; Rationale Sec. 3.5.4.1; H&S Sec. 4.4.4 p. 81.

11.10: Why can't I pass a char ** to a function which expects a const char **? A: You can use a pointer-to-T (for any type T) where a pointer-toconst-T is expected. However, the rule (an explicit exception) which permits slight mismatches in qualified pointer types is not applied recursively, but only at the top level. You must use explicit casts (e.g. (const char **) in this case) when assigning (or passing) pointers which have qualifier mismatches at other than the first level of indirection. References: ISO Sec. 6.1.2.6, Sec. 6.3.16.1, Sec. 6.5.3; H&S Sec. 7.9.1 pp. 221-2. 11.12a: What's the correct declaration of main()? A: Either int main(), int main(void), or int main(int argc, char *argv[]) (with alternate spellings of argc and *argv[] obviously allowed). See also questions 11.12b to 11.15 below. References: ISO Sec. 5.1.2.2.1, Sec. G.5.1; H&S Sec. 20.1 p. 416; CT&P Sec. 3.10 pp. 50-51. 11.12b: Can I declare main() as void, to shut off these annoying "main returns no value" messages?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

No. main() must be declared as returning an int, and as taking either zero or two arguments, of the appropriate types. If you're calling exit() but still getting warnings, you may have to insert a redundant return statement (or use some kind of "not reached" directive, if available). Declaring a function as void does not merely shut off or rearrange warnings: it may also result in a different function call/return sequence, incompatible with what the caller (in main's case, the C run-time startup code) expects. (Note that this discussion of main() pertains only to "hosted" implementations; none of it applies to "freestanding" implementations, which may not even have main(). However, freestanding implementations are comparatively rare, and if you're using one, you probably know it. If you've never heard of the distinction, you're probably using a hosted implementation, and the above rules apply.) References: ISO Sec. 5.1.2.2.1, Sec. G.5.1; H&S Sec. 20.1 p. 416; CT&P Sec. 3.10 pp. 50-51.

11.13: But what about main's third argument, envp? A: It's a non-standard (though common) extension. If you really need to access the environment in ways beyond what the standard getenv() function provides, though, the global variable environ is probably a better avenue (though it's equally non-standard). References: ISO Sec. G.5.1; H&S Sec. 20.1 pp. 416-7. 11.14: I believe that declaring void main() can't fail, since I'm calling exit() instead of returning, and anyway my operating system ignores a program's exit/return status. A: It doesn't matter whether main() returns or not, or whether anyone looks at the status; the problem is that when main() is

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

misdeclared, its caller (the runtime startup code) may not even be able to *call* it correctly (due to the potential clash of calling conventions; see question 11.12b). It has been reported that programs using void main() and compiled using BC++ 4.5 can crash. Some compilers (including DEC C V4.1 and gcc with certain warnings enabled) will complain about void main(). Your operating system may ignore the exit status, and void main() may work for you, but it is not portable and not correct. 11.15: The book I've been using, _C Programing for the Compleat Idiot_, always uses void main(). A: Perhaps its author counts himself among the target audience. Many books unaccountably use void main() in examples, and assert that it's correct. They're wrong.

11.16: Is exit(status) truly equivalent to returning the same status from main()? A: Yes and no. The Standard says that they are equivalent. However, a return from main() cannot be expected to work if data local to main() might be needed during cleanup; see also question 16.4. A few very old, nonconforming systems may once have had problems with one or the other form. (Finally, the two forms are obviously not equivalent in a recursive call to main().) References: K&R2 Sec. 7.6 pp. 163-4; ISO Sec. 5.1.2.2.3. 11.17: I'm trying to use the ANSI "stringizing" preprocessing operator `#' to insert the value of a symbolic constant into a message, but it keeps stringizing the macro's name rather than its value. A: You can use something like the following two-step procedure to

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

force a macro to be expanded as well as stringized: #define Str(x) #x #define Xstr(x) Str(x) #define OP plus char *opname = Xstr(OP); This code sets opname to "plus" rather than "OP". An equivalent circumlocution is necessary with the token-pasting operator ## when the values (rather than the names) of two macros are to be concatenated. References: ISO Sec. 6.8.3.2, Sec. 6.8.3.5. 11.18: What does the message "warning: macro replacement within a string literal" mean? A: Some pre-ANSI compilers/preprocessors interpreted macro definitions like #define TRACE(var, fmt) printf("TRACE: var = fmt\n", var) such that invocations like TRACE(i, %d); were expanded as printf("TRACE: i = %d\n", i); In other words, macro parameters were expanded even inside string literals and character constants. Macro expansion is *not* defined in this way by K&R or by Standard C. When you do want to turn macro arguments into strings, you can use the new # preprocessing operator, along with string literal concatenation (another new ANSI feature):

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#define TRACE(var, fmt) \ printf("TRACE: " #var " = " #fmt "\n", var) See also question 11.17 above. References: H&S Sec. 3.3.8 p. 51. 11.19: I'm getting strange syntax errors inside lines I've #ifdeffed out. A: Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef must still consist of "valid preprocessing tokens." This means that the characters " and ' must each be paired just as in real C code, and the pairs mustn't cross line boundaries. (Note particularly that an apostrophe within a contracted word looks like the beginning of a character constant.) Therefore, natural-language comments and pseudocode should always be written between the "official" comment delimiters /* and */. (But see question 20.20, and also 10.25.) References: ISO Sec. 5.1.1.2, Sec. 6.1; H&S Sec. 3.2 p. 40. 11.20: What are #pragmas and what are they good for? A: The #pragma directive provides a single, well-defined "escape hatch" which can be used for all sorts of (nonportable) implementation-specific controls and extensions: source listing control, structure packing, warning suppression (like lint's old /* NOTREACHED */ comments), etc. References: ISO Sec. 6.8.6; H&S Sec. 3.7 p. 61. 11.21: What does "#pragma once" mean? A: I found it in some header files.

It is an extension implemented by some preprocessors to help make header files idempotent; it is equivalent to the #ifndef trick mentioned in question 10.7, though less portable.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

11.22: Is char a[3] = "abc"; legal? A:

What does it mean?

It is legal in ANSI C (and perhaps in a few pre-ANSI systems), though useful only in rare circumstances. It declares an array of size three, initialized with the three characters 'a', 'b', and 'c', *without* the usual terminating '\0' character. The array is therefore not a true C string and cannot be used with strcpy, printf %s, etc. Most of the time, you should let the compiler count the initializers when initializing arrays (in the case of the initializer "abc", of course, the computed size will be 4). References: ISO Sec. 6.5.7; H&S Sec. 4.6.4 p. 98.

11.24: Why can't I perform arithmetic on a void * pointer? A: The compiler doesn't know the size of the pointed-to objects. Before performing arithmetic, convert the pointer either to char * or to the pointer type you're trying to manipulate (but see also question 4.5). References: ISO Sec. 6.1.2.5, Sec. 6.3.6; H&S Sec. 7.6.2 p. 204. 11.25: What's the difference between memcpy() and memmove()? A: memmove() offers guaranteed behavior if the source and destination arguments overlap. memcpy() makes no such guarantee, and may therefore be more efficiently implementable. When in doubt, it's safer to use memmove(). References: K&R2 Sec. B3 p. 250; ISO Sec. 7.11.2.1, Sec. 7.11.2.2; Rationale Sec. 4.11.2; H&S Sec. 14.3 pp. 341-2; PCS Sec. 11 pp. 165-6. 11.26: What should malloc(0) do? 0 bytes? Return a null pointer or a pointer to

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

The ANSI/ISO Standard says that it may do either; the behavior is implementation-defined (see question 11.33). References: ISO Sec. 7.10.3; PCS Sec. 16.1 p. 386.

11.27: Why does the ANSI Standard not guarantee more than six caseinsensitive characters of external identifier significance? A: The problem is older linkers which are under the control of neither the ANSI/ISO Standard nor the C compiler developers on the systems which have them. The limitation is only that identifiers be *significant* in the first six characters, not that they be restricted to six characters in length. This limitation is marked in the Standard as "obsolescent", and will be removed in C9X. References: ISO Sec. 6.1.2, Sec. 6.9.1; Rationale Sec. 3.1.2; C9X Sec. 6.1.2; H&S Sec. 2.5 pp. 22-3. 11.29: My compiler is rejecting the simplest possible test programs, with all kinds of syntax errors. A: Perhaps it is a pre-ANSI compiler, unable to accept function prototypes and the like. See also questions 1.31, 10.9, 11.30, and 16.1b. 11.30: Why are some ANSI/ISO Standard library functions showing up as undefined, even though I've got an ANSI compiler? A: It's possible to have a compiler available which accepts ANSI syntax, but not to have ANSI-compatible header files or run-time libraries installed. (In fact, this situation is rather common when using a non-vendor-supplied compiler such as gcc.) See also questions 11.29, 13.25, and 13.26.

11.31: Does anyone have a tool for converting old-style C programs to

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

ANSI C, or vice versa, or for automatically generating prototypes? A: Two programs, protoize and unprotoize, convert back and forth between prototyped and "old style" function definitions and declarations. (These programs do *not* handle full-blown translation between "Classic" C and ANSI C.) These programs are part of the FSF's GNU C compiler distribution; see question 18.3. The unproto program (/pub/unix/unproto5.shar.Z on ftp.win.tue.nl) is a filter which sits between the preprocessor and the next compiler pass, converting most of ANSI C to traditional C on-the-fly. The GNU GhostScript package comes with a little program called ansi2knr. Before converting ANSI C back to old-style, beware that such a conversion cannot always be made both safely and automatically. ANSI C introduces new features and complexities not found in K&R C. You'll especially need to be careful of prototyped function calls; you'll probably need to insert explicit casts. See also questions 11.3 and 11.29. Several prototype generators exist, many as modifications to lint. A program called CPROTO was posted to comp.sources.misc in March, 1992. There is another program called "cextract." Many vendors supply simple utilities like these with their compilers. See also question 18.16. (But be careful when generating prototypes for old functions with "narrow" parameters; see question 11.3.) 11.32: Why won't the Frobozz Magic C Compiler, which claims to be ANSI compliant, accept this code? I know that the code is ANSI, because gcc accepts it. A: Many compilers support a few non-Standard extensions, gcc more

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

so than most. Are you sure that the code being rejected doesn't rely on such an extension? It is usually a bad idea to perform experiments with a particular compiler to determine properties of a language; the applicable standard may permit variations, or the compiler may be wrong. See also question 11.35. 11.33: People seem to make a point of distinguishing between implementation-defined, unspecified, and undefined behavior. What's the difference? A: Briefly: 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?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 6.1.2.5, Sec. 7.9.1, Sec. 7.9.7.5; 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 endof-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. 7.9.7.1, Sec. 7.9.10.2; 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.9.5.2.

12.5:

How can I read one character at a time, without waiting for the RETURN key? See question 19.1. How can I print a '%' character in a printf format string? tried \%, but it didn't work. 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. 7.9.6.1. I

A: 12.6:

A:

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? 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.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.9.6.1, Sec. 7.9.6.2; 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, conservativelysized 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. 7.9.6.1; 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.9.6.2; 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().

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.9.6.2; 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. 7.9.6.2; H&S Sec. 15.8 pp. 357-64. 12.20: Why does everyone say not to use scanf()? instead? A: What should I use

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 overconservative. (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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 lengthlimited 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 fullyformatted string. References: C9X Sec. 7.13.6.6. 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 4.9.7.2; 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. 7.9.10.3; 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. 7.9.9.1,7.9.9.3; 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?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.9.5.2; 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. 7.9.5.3. 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. 7.9.5.4; H&S Sec. 15.2. 12.34: Once I've used freopen(), how can I get the original stdout (or

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.9.5.3; H&S Sec. 15.2.1 p. 348.

Section 13. Library Functions

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

13.1:

How can I convert numbers to strings (the opposite of atoi)? Is there an itoa() function? 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 floatingpoint numbers to strings as well (using %ld or %f). References: K&R1 Sec. 3.6 p. 60; K&R2 Sec. 3.6 p. 64.

A:

13.2:

Why does strncpy() not always place a '\0' terminator in the destination string? 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().

A:

13.5:

Why do some versions of toupper() act strangely if given an upper-case letter? Why does some code call islower() before toupper()? Older versions of toupper() and tolower() did not always work correctly on arguments which did not need converting (i.e. on

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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. 7.11.5.8; H&S Sec. 13.7 pp. 333-4; PCS p. 178. 13.7: A: I need some code to do regular expression and wildcard matching. 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, freelyredistributable 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 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. 7.10.5.2; H&S Sec. 20.5 p. 419. 13.9: Now I'm trying to sort an array of structures with qsort(). comparison function takes pointers to structures, but the My

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 . In general, it is a bad idea to insert casts just to "shut the compiler up." 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. 7.10.5.2; 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.12.2.3; H&S Sec. 18.4 pp. 401-2. 13.14: How can I add N days to a date? between two dates? A: How can I find the difference

The ANSI/ISO Standard C mktime() and difftime() functions provide some support for both problems. mktime() accepts nonnormalized 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).

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.12.2.2,7.12.2.3; 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); will have grave y2k problems indeed. /* WRONG */ 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.10.2.1; 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.10.2.2; 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. 3.2.1.1 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

old program. Why do I get "undefined external" errors for: index? rindex? bcopy?

obsolete; you should instead:

bcmp? bzero?

use strchr. use strrchr. use memmove, after interchanging the first and second arguments (see also question 11.25). use memcmp. 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? Most computers use base 2 for floating-point numbers as well as for integers. In base 2, one divided by ten is an infinitelyrepeating 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. I'm trying to take some square roots, but I'm getting crazy numbers. 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:

14.2:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Make sure instance, the *end* questions

you're actually linking with the math library. For under Unix, you usually need to use the -lm option, at of the command line, when compiling/linking. See also 13.25, 13.26, and 14.2.

14.4:

My floating-point calculations are acting strangely and giving me different answers on different machines. 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".

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

14.5:

What's a good way to check for "close enough" floating-point equality? 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) 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.

A:

/* WRONG */

14.6: A:

How do I round numbers? 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: A:

Why doesn't C have an exponentiation operator? Because few processors have an exponentiation instruction.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

C has a pow() function, declared in <math.h>, although explicit multiplication is usually better for small positive integral exponents. References: ISO Sec. 7.5.5.1; 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>. 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: A: How do I test for IEEE NaN and other special values? 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.

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 6.1.2.5, 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.)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Section 15. Variable-Length Argument Lists 15.1: I heard that you have to #include <stdio.h> before calling printf(). Why? 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. 6.3.2.2, Sec. 7.1.7; Rationale Sec. 3.3.2.2, 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? 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. 6.3.2.2; 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

A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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> #include <stdarg.h> #include <string.h> /* for malloc, NULL, size_t */ /* for va_ stuff */ /* for strcat et al. */

A:

char *vstrcat(char *first, ...) { size_t len; char *retbuf; va_list argp; char *p; if(first == NULL) return NULL; len = strlen(first);

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) len += strlen(p); va_end(argp); retbuf = malloc(len + 1); if(retbuf == NULL) return NULL; (void)strcpy(retbuf, first); va_start(argp, first); /* restart; 2nd scan */ /* +1 for trailing \0 */

/* error */

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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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. 7.9.6.7,7.9.6.8,7.9.6.9; H&S Sec. 15.12 pp. 379-80; PCS Sec. 11 pp. 186-7.

A:

15.6:

How can I write a function analogous to scanf(), that calls scanf() to do most of the work? C9X will support vscanf(), vfscanf(), and vsscanf(). (Until then, you may be on your own.) References: C9X Secs. 7.3.6.12-14.

A:

15.7:

I have a pre-ANSI compiler, without <stdarg.h>.

What can I do?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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.

A:

15.9:

My compiler isn't letting me declare a function int f(...) { }

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 6.5.4.3, Sec. 7.8.1.1; H&S Sec. 9.2 p. 263. 15.10: I have a varargs function which accepts a float parameter. 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. 6.3.2.2; Rationale Sec. 4.8.1.2; H&S Sec. 11.4 p. 297. 15.11: I can't get va_arg() to pull in an argument of type pointer-tofunction. A: The type-rewriting games which the va_arg() macro typically plays are stymied by overly-complicated types such as pointer-tofunction. If you use a typedef for the function pointer type, however, all will be well. See also question 1.21. Why

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: ISO Sec. 7.8.1.2; Rationale Sec. 4.8.1.2. 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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.) The compiler seems to skip

16.1c: Why isn't my procedure call working? 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().) 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? 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

A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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... 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: A: What do "Segmentation violation" and "Bus error" mean? These generally mean that your program tried to access memory it shouldn't have, invariably as a result of stack corruption or

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: A: What's the best style for code layout in C? 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: A: Why do some people write if(0 == x) instead of if(x == 0)? 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

17.5:

I came across some code that puts a (void) cast before each call to printf(). Why? 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.

A:

17.8: A:

What is "Hungarian Notation"?

Is it worthwhile?

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? Various documents are available for anonymous ftp from: Site: ftp.cs.washington.edu File or directory: pub/cstyle.tar.Z (the updated Indian Hill guide)

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

ftp.cs.toronto.edu

doc/programming (including Henry Spencer's "10 Commandments for C Programmers") pub/style-guide

ftp.cs.umd.edu

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: cflow, cxref, calls, cscope, xscope, or ixfw cb, indent, GNU indent, or vgrind CVS, RCS, or SCCS

a C cross-reference generator a C beautifier/prettyprinter a revision control or configuration management tool a C source obfuscator (shrouder) a "make" dependency generator tools to compute code metrics

obfus, shroud, or opqcp

makedepend, or try cc -M or cpp -M ccount, Metre, lcount, or csize, or see URL http://www.qucis.queensu.ca/ Software-Engineering/Cmetrics.html ; there is also a package sold by McCabe and Associates this can be done very crudely with the standard Unix utility wc, and somewhat better with grep -c ";" check volume 14 of

a C lines-of-source counter

a C declaration aid

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(cdecl)

comp.sources.unix (see question 18.16) and K&R2 see question 11.31

a prototype generator a tool to track down malloc problems a "selective" C preprocessor language translation tools C verifiers (lint) a C compiler!

see question 18.2

see question 10.18 see questions 11.31 and 20.26 see question 18.7 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: A: How can I track down these pesky malloc problems? 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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, 603-889-2386. CodeCenter (formerly Saber-C) from Centerline Software, 10 Fawcett Street, Cambridge, MA 02138, USA, 617-498-3000. Insight, from ParaSoft Corporation, 2500 E. Foothill Blvd., Pasadena, CA 91107, USA, 818-792-9941, insight@parasoft.com . Purify, from Pure Software, 1309 S. Mary Ave., Sunnyvale, CA 94087, USA, 800-224-7873, http://www.pure.com/ , info-home@pure.com . (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, 630-620-5000, 800-442-6861, info@platinum.com, www.platinum.com . ZeroFault, from The Kernel Group, 1250 Capital of Texas Highway South, Building Three, Suite 601, Austin, TX 78746, 512-433-3333, http://www.tkg.com/, zf@tkg.com . 18.3: A: What's a free or cheap C compiler I can use? 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 .

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A very inexpensive MS-DOS compiler is Power C from Mix Software, 1132 Commerce Drive, Richardson, TX 75801, USA, 214-783-6001. 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/compilerslist/. (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. you see anything wrong with it? Can

A:

See if you can run lint first (perhaps with the -a, -c, -h, -p or other options). Many C compilers are really only halfcompilers, 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_ .

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

18.5:

How can I shut off the "warning: possible pointer alignment problem" message which lint gives me for each call to malloc()? 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.) Where can I get an ANSI-compatible lint? 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 (+1) 610 584 4261 gimpel@netaxs.com

A:

18.7: A:

USA

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 higherlevel 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 .)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

18.8: A:

Don't ANSI function prototypes render lint obsolete? 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: A:

Are there any C tutorials or other resources on the net? 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 svrftp.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 .

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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).

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 ("Cminus-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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(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. 234239; 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/..../

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

/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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 lineat-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, batchoriented mainframes) perform input processing in peripheral processors which cannot be told to do anything other than lineat-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 systemspecific questions that the answer that applies to your system

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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. How can I display a percentage-done indication that updates itself in place, or show one of those "twirling baton" progress indicators? 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? 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:

19.3:

A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: A: How do I read the arrow keys? What about function keys?

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: A:

How do I read the mouse? Consult your system documentation, or ask on system-specific newsgroup (but check its FAQ handling is completely different under the X DOS, the Macintosh, and probably every other References: PCS Sec. 5.5 pp. 78-80. an appropriate list first). Mouse window system, MSsystem.

19.7: A:

How can I do serial ("comm") port I/O? It's system-dependent. Under Unix, you typically open, read, and write a device file in /dev, and use the facilities of the

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: A: How can I direct output to the printer? 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? 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 deviceindependent 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 Ccallable 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? if a requested input file is missing. A: I want to warn the user

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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.9.9.4; 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.9.4.1; 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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? The call

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 5.2.4.1; C9X Sec. 5.2.4.1. 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?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.10.4.5; 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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 5.1.2.2.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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 subsecond 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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, singletasking 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,2156; 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

References: Rationale Sec. 4.5.1. 19.40: How do I... Use sockets? applications? A: Do networking? Write client/server

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/ .) Use BIOS calls? Write ISR's? Create TSR's?

19.40b: How do I... 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. exist on other systems. They don't

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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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: A: How can I return multiple values from a function? 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. How do I access command-line arguments? 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. 114118; ISO Sec. 5.1.2.2.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? 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.

20.3: A:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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? 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: A: How can I implement sets or arrays of bits? 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 */

A:

#define BITMASK(b) (1 << ((b) % CHAR_BIT)) #define BITSLOT(b) ((b) / CHAR_BIT) #define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#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? 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

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 7.10.1.5,7.10.1.6. 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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.)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 inline 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;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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. 6.6.4.2; 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. 6.6.4.2; Rationale Sec. 3.6.4.2; H&S Sec. 8.7 p. 248. 20.19: Are the outer parentheses in return statements really optional?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 doublequoted 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. 189; PCS Sec. 10 p. 130. 20.20b: Is C a great language, or what? something like a+++++b ? Where else could you write

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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);

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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?). 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 netlib@research.att.com or research!netlib. (It is also available via anonymous ftp on netlib.att.com, in directory netlib/f2c.)

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? code? A: Can I use a C++ compiler to compile C

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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 */

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

{ 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. 7.12.2.3. 20.32: Will 2000 be a leap year? for leap years? A: Yes and no, respectively. Gregorian calendar is Is (year % 4 == 0) an accurate test

The full expression for the present

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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 memorymapped 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 mail-server@rtfm.mit.edu . 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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-48. Samuel P. Harbison and Guy L. Steele, Jr., _C: A Reference Manual_, Fourth Edition, Prentice-Hall, 1995, ISBN 0-13-326224-3. [H&S] Mark R. Horton, _Portable C Software_, Prentice Hall, 1990,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

ISBN 0-13-868050-7.

[PCS]

Institute of Electrical and Electronics Engineers, _Portable Operating System Interface (POSIX) -- Part 1: System Application Program Interface (API) [C Language]_, IEEE Std. 1003.1, ISO/IEC 9945-1. International Organization for Standardization, ISO 9899:1990 (see question 11.2). [ISO] International Organization for Standardization, WG14/N794 Working Draft (see questions 11.1 and 11.2b). [C9X] Brian W. Kernighan and P.J. Plauger, _The Elements of Programming Style_, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5. Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_, Prentice-Hall, 1978, ISBN 0-13-110163-3. [K&R1] Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_, Second Edition, Prentice Hall, 1988, ISBN 0-13-110362-8, 0-13-110370-9. (See also question 18.10.) [K&R2] Donald E. Knuth, _The Art of Computer Programming_. Volume 1: _Fundamental Algorithms_, Second Edition, Addison-Wesley, 1973, ISBN 0-201-03809-9. Volume 2: _Seminumerical Algorithms_, Second Edition, Addison-Wesley, 1981, ISBN 0-201-03822-6. Volume 3: _Sorting and Searching_, Addison-Wesley, 1973, ISBN 0-201-03803-X. (New editions are coming out!) [Knuth] Andrew Koenig, _C Traps and Pitfalls_, Addison-Wesley, 1989, ISBN 0-201-17928-8. [CT&P] G. Marsaglia and T.A. Bray, "A Convenient Method for Generating Normal Variables," _SIAM Review_, Vol. 6 #3, July, 1964. Stephen K. Park and Keith W. Miller, "Random Number Generators: Good Ones are Hard to Find," _Communications of the ACM_, Vol. 31 #10, October, 1988, pp. 1192-1201 (also technical correspondence August,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

1989, pp. 1020-1024, and July, 1993, pp. 108-110). P.J. Plauger, _The Standard C Library_, Prentice Hall, 1992, ISBN 0-13-131509-9. Thomas Plum, _C Programming Guidelines_, Second Edition, Plum Hall, 1989, ISBN 0-911537-07-4. William H. Press, Saul A. Teukolsky, William T. Vetterling, and Brian P. Flannery, _Numerical Recipes in C_, Second Edition, Cambridge University Press, 1992, ISBN 0-521-43108-5. Dale Schumacher, Ed., _Software Solutions in C_, AP Professional, 1994, ISBN 0-12-632360-7. Robert Sedgewick, _Algorithms in C_, Addison-Wesley, 1990, ISBN 0-201-51425-7. (A new edition is being prepared; the first half is ISBN 0-201-31452-5.) Charles Simonyi and Martin Heller, "The Hungarian Revolution," _Byte_, August, 1991, pp.131-138. David Straker, _C Style: Standards and Guidelines_, Prentice Hall, ISBN 0-13-116898-3. Steve Summit, _C Programming FAQs: Frequently Asked Questions_, AddisonWesley, 1995, ISBN 0-201-84519-9. [The book version of this FAQ list; see also http://www.eskimo.com/~scs/C-faq/book/Errata.html .] Sun Wu and Udi Manber, "AGREP -- A Fast Approximate Pattern-Matching Tool," USENIX Conference Proceedings, Winter, 1992, pp. 153-162. There is another bibliography in the revised Indian Hill style guide (see question 17.9). See also question 18.10.

Acknowledgements

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Thanks to Jamshid Afshar, Lauri Alanko, David Anderson, Tanner Andrews, Sudheer Apte, Joseph Arceneaux, Randall Atkinson, Rick Beem, Peter Bennett, Wayne Berke, Dan Bernstein, Tanmoy Bhattacharya, John Bickers, Gary Blaine, Yuan Bo, Mark J. Bobak, Dave Boutcher, Alan Bowler, Michael Bresnahan, Walter Briscoe, Vincent Broman, Robert T. Brown, Stan Brown, John R. Buchan, Joe Buehler, Kimberley Burchett, Gordon Burditt, Scott Burkett, Burkhard Burow, Conor P. Cahill, D'Arcy J.M. Cain, Christopher Calabrese, Ian Cargill, Vinit Carpenter, Paul Carter, Mike Chambers, Billy Chambless, C. Ron Charlton, Franklin Chen, Jonathan Chen, Raymond Chen, Richard Cheung, Avinash Chopde, Steve Clamage, Ken Corbin, Dann Corbit, Ian Cottam, Russ Cox, Jonathan Coxhead, Lee Crawford, Nick Cropper, Steve Dahmer, Andrew Daviel, James Davies, John E. Davis, Ken Delong, Norm Diamond, Bob Dinse, Jeff Dunlop, Ray Dunn, Stephen M. Dunn, Michael J. Eager, Scott Ehrlich, Arno Eigenwillig, Yoav Eilat, Dave Eisen, Joe English, Bjorn Engsig, David Evans, Clive D.W. Feather, Dominic Feeley, Simao Ferraz, Chris Flatters, Rod Flores, Alexander Forst, Steve Fosdick, Jeff Francis, Ken Fuchs, Tom Gambill, Dave Gillespie, Samuel Goldstein, Tim Goodwin, Alasdair Grant, Ron Guilmette, Doug Gwyn, Michael Hafner, Darrel Hankerson, Tony Hansen, Douglas Wilhelm Harder, Elliotte Rusty Harold, Joe Harrington, Des Herriott, Guy Harris, John Hascall, Ger Hobbelt, Jos Horsmeier, Syed Zaeem Hosain, Blair Houghton, James C. Hu, Chin Huang, David Hurt, Einar Indridason, Vladimir Ivanovic, Jon Jagger, Ke Jin, Kirk Johnson, Larry Jones, Arjan Kenter, Bhaktha Keshavachar, James Kew, Darrell Kindred, Lawrence Kirby, Kin-ichi Kitano, Peter Klausler, John Kleinjans, Andrew Koenig, Tom Koenig, Adam Kolawa, Jukka Korpela, Ajoy Krishnan T, Jon Krom, Markus Kuhn, Deepak Kulkarni, Oliver Laumann, John Lauro, Felix Lee, Mike Lee, Timothy J. Lee, Tony Lee, Marty Leisner, Dave Lewis; Don Libes, Brian Liedtke, Philip Lijnzaad, Keith Lindsay, Yen-Wei Liu, Paul Long, Christopher Lott, Tim Love, Tim McDaniel, J. Scott McKellar, Kevin McMahon, Stuart MacMartin, John R. MacMillan, Robert S. Maier, Andrew Main, Bob Makowski, Evan Manning, Barry Margolin, George Marsaglia, George Matas, Brad Mears, Wayne Mery, De Mickey, Rich Miller, Roger Miller, Bill Mitchell, Mark Moraes, Darren Morby, Bernhard Muenzer, David Murphy, Walter Murray, Ralf Muschall, Ken Nakata, Todd Nathan, Taed Nelson, Landon Curt Noll, Tim Norman, Paul Nulsen, David O'Brien, Richard A. O'Keefe, Adam Kolawa, Keith Edward O'hara, James Ojaste, Max Okumoto, Hans Olsson, Bob Peck, Andrew Phillips, Christopher Phillips,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Francois Pinard, Nick Pitfield, Wayne Pollock, Polver@aol.com, Dan Pop, Claudio Potenza, Lutz Prechelt, Lynn Pye, Kevin D. Quitt, Pat Rankin, Arjun Ray, Eric S. Raymond, Peter W. Richards, James Robinson, Eric Roode, Manfred Rosenboom, J. M. Rosenstock, Rick Rowe, Erkki Ruohtula, John Rushford, Kadda Sahnine, Tomohiko Sakamoto, Matthew Saltzman, Rich Salz, Chip Salzenberg, Matthew Sams, Paul Sand, DaviD W. Sanderson, Frank Sandy, Christopher Sawtell, Jonas Schlein, Paul Schlyter, Doug Schmidt, Rene Schmit, Russell Schulz, Dean Schulze, Jens Schweikhardt, Chris Sears, Peter Seebach, Patricia Shanahan, Aaron Sherman, Raymond Shwake, Nathan Sidwell, Peter da Silva, Joshua Simons, Ross Smith, Henri Socha, Leslie J. Somos, Henry Spencer, David Spuler, Frederic Stark, James Stern, Zalman Stern, Michael Sternberg, Geoff Stevens, Alan Stokes, Bob Stout, Dan Stubbs, Steve Sullivan, Melanie Summit, Erik Talvola, Dave Taylor, Clarke Thatcher, Wayne Throop, Chris Torek, Steve Traugott, Nikos Triantafillis, Ilya Tsindlekht, Andrew Tucker, Goran Uddeborg, Rodrigo Vanegas, Jim Van Zandt, Wietse Venema, Tom Verhoeff, Ed Vielmetti, Larry Virden, Chris Volpe, Mark Warren, Alan Watson, Kurt Watzka, Larry Weiss, Martin Weitzel, Howard West, Tom White, Freek Wiedijk, Tim Wilson, Dik T. Winter, Lars Wirzenius, Dave Wolverton, Mitch Wright, Conway Yee, Ozan S. Yigit, and Zhuo Zang, who have contributed, directly or indirectly, to this article. Thanks to the reviewers of the book-length version: Mark Brader, Vinit Carpenter, Stephen Clamage, Jutta Degener, Doug Gwyn, Karl Heuer, and Joseph Kent. Thanks to Debbie Lafferty and Tom Stone at Addison-Wesley for encouragement, and permission to cross-pollinate this list with new text from the book. Special thanks to Karl Heuer, Jutta Degener, and particularly to Mark Brader, who (to borrow a line from Steve Johnson) have goaded me beyond my inclination, and occasionally beyond my endurance, in relentless pursuit of a better FAQ list. Steve Summit scs@eskimo.com

This article is Copyright 1990-1999 by Steve Summit. Content from the book _C Programming FAQs: Frequently Asked Questions_ is made available here by permission of the author and the publisher as a service to the community. It is intended to complement the use of the

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

published text and is protected by international copyright laws. The content is made available here and may be accessed freely for personal use but may not be republished without permission. With the exception of the examples by other, cited authors (i.e. in questions 20.31 and 20.35) the C code in this article is public domain and may be used without restriction. [ By Archive-name | By Author | By Category | By Newsgroup ] [ Home | Latest Updates | Archive Stats | Search | Usenet References | Help ]

Send corrections/additions to the FAQ Maintainer: scs@eskimo.com


Last Update April 03 2002 @ 09:27 PM

comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ)


From: scs@eskimo.com (Steve Summit) Newsgroups: comp.lang.c,comp.lang.c.moderated,comp.answers,news.answers Subject: comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ) Followup-To: poster Date: 15 Mar 2002 11:00:06 GMT Organization: better late than never Expires: 3 Apr 2002 00:00:00 GMT Message-ID: <2002Mar15.0600.scs.0001@eskimo.com> Reply-To: scs@eskimo.com X-Trace: eskinews.eskimo.com 1016190006 16596 204.122.16.13 (15 Mar 2002 11:00:06 GMT) X-Complaints-To: abuse@eskimo.com NNTP-Posting-Date: 15 Mar 2002 11:00:06 GMT X-Last-Modified: February 7, 1999 X-Archive-Name: C-faq/abridged X-Version: 3.5a

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

X-URL: http://www.eskimo.com/~scs/C-faq/top.html X-PGP-Signature: Version: 2.6.2 iQCSAwUBMjhNk96sm4I1rmP1AQEF/QPndRyxOJtumiupKJiAkknSZsQr+8RTntjh zx8054S9qgdEOgpx3QHea681LklR8g51w+k04fxFU9VeRNuRh6I9yTWG1JjPZRpf NkcthDa8uNQ0JtWYWef2Jk7/sc2A0L88fHBpnG2epI5av2FwcqO3JKGNR4YkRCb6 MM80Pcg= =amQx Archive-name: C-faq/abridged Comp-lang-c-archive-name: C-FAQ-list.abridged URL: http://www.eskimo.com/~scs/C-faq/top.html [Last modified February 7, 1999 by scs.] This article is Copyright 1990-1999 by Steve Summit. Content from the book _C Programming FAQs: Frequently Asked Questions_ is made available here by permission of the author and the publisher as a service to the community. It is intended to complement the use of the published text and is protected by international copyright laws. The content is made available here and may be accessed freely for personal use but may not be republished without permission. This article contains minimal answers to the comp.lang.c frequentlyasked questions list. More detailed explanations and references can be found in the long version (posted on the first of each month, or see question 20.40 for availability), and in the web version at http://www.eskimo.com/~scs/C-faq/top.html , and in the book _C Programming FAQs: Frequently Asked Questions_ (Addison-Wesley, 1996, ISBN 0-201-84519-9). Section 1. Declarations and Initializations 1.1: A: How do you decide which integer type to use? If you might need large values (tens of thousands), use long. Otherwise, if space is very important, use short. Otherwise, use int. What should the 64-bit type on a machine that can support it?

1.4:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A: 1.7: A:

C9X specifies long long. What's the best way to declare and define global variables? The best arrangement is to place each definition in some relevant .c file, with an external declaration in a header file. What does extern mean in a function declaration? Nothing, really; the keyword extern is optional here. What's the auto keyword good for? Nothing. I can't seem to define a linked list node which contains a pointer to itself. Structures in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters? char *(*(*a[N])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier. How can I declare a function that returns a pointer to a function of its own type? You can't quite do it directly. Use a cast, or wrap a struct around the pointer and return that. My compiler is complaining about an invalid redeclaration of a

1.11: A: 1.12: A: 1.14:

A:

1.21:

A:

1.22:

A:

1.25:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

function, but I only define it once. A: Calling an undeclared function declares it implicitly as returning int.

1.25b: What's the right declaration for main()? A: 1.30: See questions 11.12a to 11.15. What am I allowed to assume about the initial values of variables which are not explicitly initialized? Uninitialized variables with "static" duration start out as 0, as if the programmer had initialized them. Variables with "automatic" duration, and dynamically-allocated memory, start out containing garbage (with the exception of calloc). Why can't I initialize a local array with a string? Perhaps you have a pre-ANSI compiler.

A:

1.31: A:

1.31b: What's wrong with "char *p = malloc(10);" ? A: Function calls are not allowed in initializers for global or static variables. What is the difference between char a[] = "string"; and char *p = "string"; ? The first declares an initialized and modifiable array; the second declares a pointer initialized to a not-necessarilymodifiable constant string. How do I initialize a pointer to a function? Use something like "extern int func(); int (*fp)() = func;" .

1.32:

A:

1.34: A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Section 2. Structures, Unions, and Enumerations 2.1: What's the difference between struct x1 { ... }; and typedef struct { ... } x2; ? The first structure is named by a tag, the second by a typedef name. Why doesn't "struct x { ... }; x thestruct;" work? C is not C++. Can a structure contain a pointer to itself? See question 1.14. What's the best way of implementing opaque (abstract) data types in C? One good way is to use structure pointers which point to structure types which are not publicly defined. I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make it act like the array had several elements. Is this legal or portable? An official interpretation has deemed that it is not strictly conforming with the C Standard. I heard that structures could be assigned to variables and passed to and from functions, but K&R1 says not. These operations are supported by all modern compilers. Is there a way to compare structures automatically? No.

A:

2.2: A: 2.3: A: 2.4:

A:

2.6:

A:

2.7:

A: 2.8: A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

2.10:

Can I pass constant values to functions which accept structure arguments? Not yet. As of this writing, C has no way of generating anonymous structure values. How can I read/write structures from/to data files? It is relatively straightforward to use fread and fwrite. How can I turn off structure padding? There is no standard method. Why does sizeof report a larger size than I expect for a structure type? The alignment of arrays of structures must be preserved. How can I determine the byte offset of a field within a structure? ANSI C defines the offsetof() macro, which should be used if available. How can I access structure fields by name at run time? Build a table of names and offsets, using the offsetof() macro. I have a program which works correctly, but dumps core after it finishes. Why? Check to see if a structure type declaration just before main() is missing its trailing semicolon, causing main() to be declared as returning a structure. See also questions 10.9 and 16.4. Can I initialize unions?

A:

2.11: A: 2.12: A: 2.13:

A: 2.14:

A:

2.15: A: 2.18:

A:

2.20:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

The current C Standard allows an initializer for the first-named member. What is the difference between an enumeration and a set of preprocessor #defines? At the present time, there is little difference. The C Standard states that enumerations are compatible with integral types. Is there an easy way to print enumeration values symbolically? No.

2.22:

A:

2.24: A:

Section 3. Expressions 3.1: A: Why doesn't the code "a[i] = i++;" work? The variable i is both referenced and modified in the same expression. Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++);" prints 49. Regardless of the order of evaluation, shouldn't it print 56? The operations implied by the postincrement and postdecrement operators ++ and -- are performed at some time after the operand's former values are yielded and before the end of the expression, but not necessarily immediately after, or before other parts of the expression are evaluated. What should the code "int i = 3; i = i++;" do? The expression is undefined. Here's a slick expression: "a ^= b ^= a ^= b". without using a temporary. It swaps a and b

3.2:

A:

3.3: A: 3.3b:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A: 3.4: A:

Not portably; its behavior is undefined. Don't precedence and parentheses dictate order of evaluation? Operator precedence and explicit parentheses impose only a partial ordering on the evaluation of an expression, which does not generally include the order of side effects. But what about the && and || operators? There is a special exception for those operators: left-to-right evaluation is guaranteed. What's a "sequence point"? A point (at the end of a full expression, or at the ||, &&, ?:, or comma operators, or just before a function call) at which all side effects are guaranteed to be complete. So given a[i] = i++; we don't know which cell of a[] gets written to, but i does get incremented by one, right? *No*. Once an expression or program becomes undefined, *all* aspects of it become undefined. If I'm not using the value of the expression, should I use i++ or ++i to increment a variable? Since the two forms differ only in the value yielded, they are entirely equivalent when only their side effect is needed. Why doesn't the code "int a = 1000, b = 1000; long int c = a * b;" work? You must manually cast one of the operands to (long). Can I use ?: on the left-hand side of an assignment expression?

3.5: A:

3.8: A:

3.9:

A:

3.12:

A:

3.14:

A: 3.16:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

No.

Section 4. Pointers 4.2: A: 4.3: A: What's wrong with "char *p; *p = malloc(10);"? The pointer you declared is p, not *p. Does *p++ increment p, or what it points to? *p++ increments p. (*p)++ . To increment the value pointed to by p, use

4.5:

I want to use a char * pointer to step over some ints. doesn't "((int *)p)++;" work?

Why

A:

In C, a cast operator is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++. I have a function which accepts, and is supposed to initialize, a pointer, but the pointer in the caller remains unchanged. The called function probably altered only the passed copy of the pointer. Can I use a void ** pointer as a parameter so that a function can accept a generic pointer by reference? Not portably. I have a function which accepts a pointer to an int. pass a constant like 5 to it? You will have to declare a temporary variable. How can I

4.8:

A:

4.9:

A: 4.10:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

4.11: A: 4.12:

Does C even have "pass by reference"? Not really, though it can be simulated. I've seen different methods used for calling functions via pointers. The extra parentheses and explicit * are now officially optional, although some older implementations require them.

A:

Section 5. Null Pointers 5.1: A: What is this infamous null pointer, anyway? For each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is not the address of any object or function. How do I get a null pointer in my programs? A constant 0 in a pointer context is converted into a null pointer at compile time. A "pointer context" is an initialization, assignment, or comparison with one side a variable or expression of pointer type, and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. In other contexts (function arguments without prototypes, or in the variable part of variadic function calls) a constant 0 with an appropriate explicit cast is required. Is the abbreviated pointer comparison "if(p)" to test for nonnull pointers valid? Yes. The construction "if(p)" works, regardless of the internal representation of null pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer.

5.2: A:

5.3:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

5.4: A:

What is NULL and how is it #defined? NULL is simply a preprocessor macro, #defined as 0 (or ((void *)0)), which is used (as a stylistic convention, in preference to unadorned 0's) to generate null pointers. How should NULL be defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? The same as on any other machine: as 0. (The compiler makes the translation, upon seeing a 0, not the preprocessor; see also question 5.4.) If NULL were defined as "((char *)0)," wouldn't that make function calls which pass an uncast NULL work? Not in general. The complication is that there are machines which use different internal representations for pointers to different types of data. A cast is still required to tell the compiler which kind of null pointer is required, since it may be different from (char *)0. If NULL and 0 are equivalent as null pointer constants, which should I use? Either; the distinction is entirely stylistic. But wouldn't it be better to use NULL, in case the value of NULL changes? No. NULL is a constant zero, so a constant zero is equally sufficient. I use the preprocessor macro "#define Nullptr(type) (type *)0" to help me build null pointers of the correct type. This trick, though valid, does not buy much.

5.5:

A:

5.6:

A:

5.9:

A: 5.10:

A:

5.12:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

5.13:

This is strange. pointer is not?

NULL is guaranteed to be 0, but the null

A:

A "null pointer" is a language concept whose particular internal value does not matter. A null pointer is requested in source code with the character "0". "NULL" is a preprocessor macro, which is always #defined as 0 (or ((void *)0)). Why is there so much confusion surrounding null pointers? The fact that null pointers are represented both in source code, and internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) may seem to suggest that the value could change some day, or on some weird machine. I'm confused. stuff. I just can't understand all this null pointer

5.14: A:

5.15:

A:

A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when they are used as arguments in function calls." Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? Such a requirement would accomplish little. Seriously, have any actual machines really used nonzero null pointers? Machines manufactured by Prime, Honeywell-Bull, and CDC, as well as Symbolics Lisp Machines, have done so. What does a run-time "null pointer assignment" error mean?

5.16:

A: 5.17:

A:

5.20:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

It means that you've written, via a null pointer, to an invalid location. (See also question 16.8.)

Section 6. Arrays and Pointers 6.1: I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn't it work? The declaration extern char *a simply does not match the actual definition. Use extern char a[]. But I heard that char a[] was identical to char *a. Not at all. Arrays are not pointers. A reference like x[3] generates different code depending on whether x is an array or a pointer. So what is meant by the "equivalence of pointers and arrays" in C? An lvalue of type array-of-T which appears in an expression decays into a pointer to its first element; the type of the resultant pointer is pointer-to-T. So for an array a and pointer p, you can say "p = a;" and then p[3] and a[3] will access the same element. Why are array and pointer declarations interchangeable as function formal parameters? It's supposed to be a convenience. How can an array be an lvalue, if you can't assign to it? An array is not a "modifiable lvalue." What is the real difference between arrays and pointers?

A:

6.2: A:

6.3:

A:

6.4:

A: 6.7: A: 6.8:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Arrays automatically allocate space which is fixed in size and location; pointers are dynamic. Someone explained to me that arrays were really just constant pointers. An array name is "constant" in that it cannot be assigned to, but an array is *not* a pointer. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? Yes, array subscripting is commutative in C. The array subscripting operation a[e] is defined as being identical to *((a)+(e)). What's the difference between array and &array? The type. How do I declare a pointer to an array? Usually, you don't want to. Consider using a pointer to one of the array's elements instead. How can I set an array's size at run time? It's straightforward to use malloc() and a pointer. How can I declare local arrays of a size matching a passed-in array? Until recently, you couldn't; array dimensions had to be compiletime constants. C9X will fix this. How can I dynamically allocate a multidimensional array? The traditional solution is to allocate an array of pointers,

6.9:

A:

6.11:

A:

6.12: A: 6.13: A:

6.14: A: 6.15:

A:

6.16: A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

and then initialize each pointer to a dynamically-allocated "row." See the full list for code samples. 6.17: A: Can I simulate a non-0-based array with a pointer? Not if the pointer points outside of the block of memory it is intended to access. My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer. The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. How do I write functions which accept two-dimensional arrays when the width is not known at compile time? It's not always particularly easy. How can I use statically- and dynamically-allocated multidimensional arrays interchangeably when passing them to functions? There is no single perfect method, but see the full list for some ideas. Why doesn't sizeof properly report the size of an array which is a parameter to a function? The sizeof operator reports the size of the pointer parameter which the function actually receives.

6.18:

A:

6.19:

A: 6.20:

A:

6.21:

A:

Section 7. Memory Allocation 7.1: Why doesn't the code "char *answer; gets(answer);" work?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

The pointer variable answer has not been set to point to any valid storage. The simplest way to correct this fragment is to use a local array, instead of a pointer. I can't get strcat() to work. I tried "char *s3 = strcat(s1, s2);" but I got strange results. Again, the main problem here is that space for the concatenated result is not properly allocated. But the man page for strcat() says that it takes two char *'s as arguments. How am I supposed to know to allocate things? In general, when using pointers you *always* have to consider memory allocation, if only to make sure that the compiler is doing it for you. I just tried the code "char *p; strcpy(p, "abc");" and it worked. Why didn't it crash? You got "lucky". How much memory does a pointer variable allocate? Only enough memory to hold the pointer itself, not any memory for the pointer to point to. I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage. Make sure that the pointed-to memory is properly (i.e. not locally) allocated. So what's the right way to return a string? Return a pointer to a statically-allocated buffer, a buffer passed in by the caller, or memory obtained with malloc().

7.2:

A:

7.3:

A:

7.3b:

A: 7.3c: A:

7.5a:

A:

7.5b: A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

7.6:

Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to malloc()? Have you #included <stdlib.h>? Why does some code carefully cast the values returned by malloc to the pointer type being allocated? Before ANSI/ISO C, these casts were required to silence certain warnings. Why does so much code leave out the multiplication by sizeof(char) when allocating strings? Because sizeof(char) is, by definition, exactly 1. I've heard that some operating systems don't actually allocate malloc'ed memory until the program tries to use it. Is this legal? It's hard to say. I'm allocating a large array for some numeric work, but malloc() is acting strangely. Make sure the number you're trying to pass to malloc() isn't bigger than a size_t can hold. I've got 8 meg of memory in my PC. malloc 640K or so? Why can I only seem to

A: 7.7:

A:

7.8:

A: 7.14:

A: 7.16:

A:

7.17:

A:

Under the segmented architecture of PC compatibles, it can be difficult to use more than 640K with any degree of transparency. See also question 19.23. My program is crashing, apparently somewhere down inside malloc.

7.19:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Make sure you aren't using more memory than you malloc'ed, especially for strings (which need strlen(str) + 1 bytes). You can't use dynamically-allocated memory after you free it, can you? No. Some early documentation implied otherwise, but the claim is no longer valid. Why isn't a pointer null after calling free()? C's pass-by-value semantics mean that called functions can never permanently change the values of their arguments. When I call malloc() to allocate memory for a local pointer, do I have to explicitly free() it? Yes. When I free a dynamically-allocated structure containing pointers, do I also have to free each subsidiary pointer? Yes. Must I free allocated memory before the program exits? You shouldn't have to. Why doesn't my program's memory usage go down when I free memory? Most implementations of malloc/free do not return freed memory to the operating system. How does free() know how many bytes to free? The malloc/free implementation remembers the size of each block as it is allocated.

7.20:

A:

7.21: A:

7.22:

A: 7.23:

A: 7.24: A: 7.25:

A:

7.26: A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

7.27:

So can I query the malloc package to find out how big an allocated block is? Not portably. Is it legal to pass a null pointer as the first argument to realloc()? ANSI C sanctions this usage, although several earlier implementations do not support it. What's the difference between calloc() and malloc()? calloc() takes two arguments, and initializes the allocated memory to all-bits-0. What is alloca() and why is its use discouraged? alloca() allocates memory which is automatically freed when the function which called alloca() returns. alloca() cannot be written portably, is difficult to implement on machines without a stack, and fails under certain conditions if implemented simply.

A: 7.30:

A:

7.31: A:

7.32: A:

Section 8. Characters and Strings 8.1: A: 8.2: Why doesn't "strcat(string, '!');" work? strcat() concatenates *strings*, not characters. Why won't the test if(string == "value") correctly compare string against the value? It's comparing pointers. To compare two strings, use strcmp().

A: 8.3:

Why can't I assign strings to character arrays?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Strings are arrays, and you can't assign arrays directly. strcpy() instead.

Use

8.6:

How can I get the numeric (character set) value corresponding to a character? In C, if you have the character, you have its value. Why is sizeof('a') not 1? Character constants in C are of type int.

A: 8.9: A:

Section 9. Boolean Expressions and Variables 9.1: A: What is the right type to use for Boolean values in C? There's no one right answer; see the full list for some discussion. What if a built-in logical or relational operator "returns" something other than 1? When a Boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. (This is *not* true for some library routines such as isalpha.) Is if(p), where p is a pointer, valid? Yes. See question 5.3.

9.2:

A:

9.3: A:

Section 10. C Preprocessor 10.2: I've got some cute preprocessor macros that let me write C code that looks more like Pascal. What do y'all think?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A: 10.3: A:

Bleah. How can I write a generic macro to swap two values? There is no good answer to this question. The best all-around solution is probably to forget about using a macro. What's the best way to write a multi-statement macro? #define Func() do {stmt1; stmt2; ... } while(0) What are .h files and what should I put in them? Header files (also called ".h files") should generally contain common declarations and macro, structure, and typedef definitions, but not variable or function definitions. Is it acceptable for one header file to #include another? It's a question of style, and thus receives considerable debate. /* (no trailing ;) */

10.4: A: 10.6: A:

10.7: A:

10.8a: What's the difference between #include <> and #include "" ? A: Roughly speaking, the <> syntax is for Standard headers and "" is for project headers.

10.8b: What are the complete rules for header file searching? A: The exact behavior is implementation-defined; see the full list for some discussion. I'm getting strange syntax errors on the very first declaration in a file, but it looks fine. Perhaps there's a missing semicolon at the end of the last declaration in the last header file you're #including.

10.9:

A:

10.10b: I'm #including the header file for a function, but the linker

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

keeps saying it's undefined. A: See question 13.25.

10.11: Where can I get a copy of a missing header file? A: Contact your vendor, or see question 18.16 or the full list.

10.12: How can I construct preprocessor #if expressions which compare strings? A: You can't do it directly; try #defining several manifest constants and implementing conditionals on those.

10.13: Does the sizeof operator work in preprocessor #if directives? A: No.

10.14: Can I use an #ifdef in a #define line, to define something two different ways? A: No.

10.15: Is there anything like an #ifdef for typedefs? A: Unfortunately, no.

10.16: How can I use a preprocessor #if expression to detect endianness? A: You probably can't.

10.18: How can I preprocess some code to remove selected conditional compilations, without preprocessing everything? A: Look for a program called unifdef, rmifdef, or scpp.

10.19: How can I list all of the predefined identifiers?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

If the compiler documentation is unhelpful, try extracting printable strings from the compiler or preprocessor executable.

10.20: I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b", but it doesn't work any more. A: Try the ANSI token-pasting operator ##.

10.22: What does the message "warning: macro replacement within a string literal" mean? A: See question 11.18.

10.23-4: I'm having trouble using macro arguments inside string literals, using the `#' operator. A: See questions 11.17 and 11.18.

10.25: I've got this tricky preprocessing I want to do and I can't figure out a way to do it. A: Consider writing your own little special-purpose preprocessing tool, instead.

10.26: How can I write a macro which takes a variable number of arguments? A: Here is one popular trick. Note that the parentheses around printf's argument list are in the macro call, not the definition. #define DEBUG(args) (printf("DEBUG: "), printf args) if(n != 0) DEBUG(("n is %d\n", n));

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Section 11. ANSI/ISO Standard C 11.1: A: What is the "ANSI C Standard?" In 1983, the American National Standards Institute (ANSI) commissioned a committee to standardize the C language. Their work was ratified as ANS X3.159-1989, and has since been adopted as ISO/IEC 9899:1990, and later amended. How can I get a copy of the Standard? Copies are available from ANSI in New York, or from Global Engineering Documents in Englewood, CO, or from any national standards body, or from ISO in Geneva, or republished within one or more books. See the unabridged list for details.

11.2: A:

11.2b: Where can I get information about updates to the Standard? A: 11.3: See the full list for pointers. My ANSI compiler is complaining about prototype mismatches for parameters declared float. You have mixed the new-style prototype declaration "extern int func(float);" with the old-style definition "int func(x) float x;". "Narrow" types are treated differently according to which syntax is used. This problem can be fixed by avoiding narrow types, or by using either new-style (prototype) or old-style syntax consistently. Can you mix old-style and new-style function syntax? Doing so is currently legal, for most argument types (see question 11.3). Why does the declaration "extern int f(struct x *p);" give me a warning message?

A:

11.4: A:

11.5:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

A structure declared (or even mentioned) for the first time within a prototype cannot be compatible with other structures declared in the same source file. Why can't I use const values in initializers and array dimensions? The value of a const-qualified object is *not* a constant expression in the full sense of the term. What's the difference between "const char *p" and "char * const p"? The former declares a pointer to a constant character; the latter declares a constant pointer to a character.

11.8:

A:

11.9:

A:

11.10: Why can't I pass a char ** to a function which expects a const char **? A: The rule which permits slight mismatches in qualified pointer assignments is not applied recursively.

11.12a: What's the correct declaration of main()? A: int main(int argc, char *argv[]) .

11.12b: Can I declare main() as void, to shut off these annoying "main returns no value" messages? A: No.

11.13: But what about main's third argument, envp? A: It's a non-standard (though common) extension.

11.14: I believe that declaring void main() can't fail, since I'm calling exit() instead of returning.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

It doesn't matter whether main() returns or not, the problem is that its caller may not even be able to *call* it correctly.

11.15: The book I've been using always uses void main(). A: It's wrong.

11.16: Is exit(status) truly equivalent to returning the same status from main()? A: Yes and no. (See the full list for details.)

11.17: How do I get the ANSI "stringizing" preprocessing operator `#' to stringize the macro's value instead of its name? A: You can use a two-step #definition to force a macro to be expanded as well as stringized.

11.18: What does the message "warning: macro replacement within a string literal" mean? A: Some pre-ANSI compilers/preprocessors expanded macro parameters even inside string literals and character constants.

11.19: I'm getting strange syntax errors inside lines I've #ifdeffed out. A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This means that there must be no newlines inside quotes, and no unterminated comments or quotes (i.e. no single apostrophes).

11.20: What are #pragmas ? A: The #pragma directive provides a single, well-defined "escape hatch" which can be used for extensions.

11.21: What does "#pragma once" mean?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

It is an extension implemented by some preprocessors to help make header files idempotent.

11.22: Is char a[3] = "abc"; legal? A: Yes, in ANSI C.

11.24: Why can't I perform arithmetic on a void * pointer? A: The compiler doesn't know the size of the pointed-to objects.

11.25: What's the difference between memcpy() and memmove()? A: memmove() offers guaranteed behavior if the source and destination arguments overlap.

11.26: What should malloc(0) do? A: The behavior is implementation-defined.

11.27: Why does the ANSI Standard not guarantee more than six caseinsensitive characters of external identifier significance? A: The problem is older linkers which cannot be forced (by mere words in a Standard) to upgrade.

11.29: My compiler is rejecting the simplest possible test programs, with all kinds of syntax errors. A: Perhaps it is a pre-ANSI compiler.

11.30: Why are some ANSI/ISO Standard library functions showing up as undefined, even though I've got an ANSI compiler? A: Perhaps you don't have ANSI-compatible headers and libraries.

11.31: Does anyone have a tool for converting old-style C programs to

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

ANSI C, or for automatically generating prototypes? A: See the full list for details.

11.32: Why won't frobozz-cc, which claims to be ANSI compliant, accept this code? A: Are you sure that the code being rejected doesn't rely on some non-Standard extension?

11.33: What's the difference between implementation-defined, unspecified, and undefined behavior? A: If you're writing portable code, ignore the distinctions. Otherwise, see the full list.

11.34: I'm appalled that the ANSI Standard leaves so many issues undefined. A: In most of these cases, the Standard is simply codifying existing practice.

11.35: I just tried some allegedly-undefined code on an ANSI-conforming compiler, and got the results I expected. A: A compiler may do anything it likes when faced with undefined behavior, including doing what you expect.

Section 12. Stdio 12.1: What's wrong with the code "char c; while((c = getchar()) != EOF) ..."? The variable to hold getchar's return value must be an int. Why won't the code "while(!feof(infp)) { fgets(buf, MAXLINE, infp); fputs(buf, outfp); }" work?

A: 12.2:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A: 12.4:

EOF is only indicated *after* an input routine fails. My program's prompts and intermediate output don't always show up on the screen. It's best to use an explicit fflush(stdout) whenever output should definitely be visible. How can I read one character at a time, without waiting for the RETURN key? See question 19.1. How can I print a '%' character with printf? "%%". How can printf() use %f for type double, if scanf() requires %lf? C's "default argument promotions" mean that values of type float are promoted to double.

A:

12.5:

A: 12.6: A: 12.9:

A:

12.9b: What printf format should I use for a typedef when I don't know the underlying type? A: Use a cast to convert the value to a known type, then use the printf format matching that type.

12.10: How can I implement a variable field width with printf? A: Use printf("%*d", width, x).

12.11: How can I print numbers with commas separating the thousands? A: There is no standard routine (but see <locale.h>).

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

12.12: Why doesn't the call scanf("%d", i) work? A: The arguments you pass to scanf() must always be pointers.

12.13: Why doesn't the code "double d; scanf("%f", &d);" work? A: Unlike printf(), scanf() uses %lf for double, and %f for float.

12.15: How can I specify a variable width in a scanf() format string? A: You can't.

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: Try using "%d" instead of "%d\n".

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() and gets() do not work well together.

12.19: I'm re-prompting the user if scanf() fails, but sometimes it seems to go into an infinite loop. A: scanf() tends to "jam" on bad input since it does not discard it. What should I use

12.20: Why does everyone say not to use scanf()? instead? A:

scanf() has a number of problems. Usually, it's easier to read entire lines and then interpret them.

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()?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Use the new snprintf() function, if you can.

12.23: Why does everyone say not to use gets()? A: It cannot be prevented from overflowing the input buffer.

12.24: Why does errno contain ENOTTY after a call to printf()? A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno after an error has been reported.

12.25: What's the difference between fgetpos/fsetpos and ftell/fseek? A: fgetpos() and fsetpos() use a special typedef which may allow them to work with larger files than ftell() and fseek().

12.26: Will fflush(stdin) flush unread characters from the standard input stream? A: No.

12.30: I'm trying to update a file in place, by using fopen mode "r+", but it's not working. A: Be sure to call fseek between reading and writing.

12.33: How can I redirect stdin or stdout from within a program? A: Use freopen().

12.34: Once I've used freopen(), how can I get the original stream back? A: There isn't a good way. Try avoiding freopen.

12.36b: How can I arrange to have output go two places at once?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

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? A: Be sure to specify "rb" mode when calling fopen().

Section 13. Library Functions 13.1: A: 13.2: A: 13.5: How can I convert numbers to strings? Just use sprintf(). Why does strncpy() not always write a '\0'? For mildly-interesting historical reasons. Why do some versions of toupper() act strangely if given an upper-case letter? Older versions of toupper() and tolower() did not always work as expected in this regard. How can I split up a string into whitespace-separated fields? Try strtok(). I need some code to do regular expression and wildcard matching. regexp libraries abound; see the full list for details. I'm trying to sort an array of strings with qsort(), using strcmp() as the comparison function, but it's not working. You'll have to write a "helper" comparison function which takes two generic pointer arguments, converts them to char **, and dereferences them, yielding char *'s which can be usefully

A:

13.6: A: 13.7: A: 13.8:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

compared. 13.9: Now I'm trying to sort an array of structures, but the compiler is complaining that the function is of the wrong type for qsort(). The comparison function must be declared as accepting "generic pointers" (const void *) which it then converts to structure pointers.

A:

13.10: How can I sort a linked list? A: Algorithms like insertion sort and merge sort work well, or you can keep the list in order as you build it.

13.11: How can I sort more data than will fit in memory? A: You want an "external sort"; see the full list for details.

13.12: How can I get the time of day in a C program? A: Just use the time(), ctime(), localtime() and/or strftime() functions.

13.13: How can I convert a struct tm or a string into a time_t? A: The ANSI mktime() function converts a struct tm to a time_t. standard routine exists to parse strings. No

13.14: How can I perform calendar manipulations? A: The ANSI/ISO Standard C mktime() and difftime() functions provide some support for both problems.

13.14b: Does C have any Year 2000 problems? A: No, although poorly-written C programs do. Make sure you know that tm_year holds the value of the year minus 1900.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

13.15: I need a random number generator. A: The Standard C library has one: rand().

13.16: How can I get random integers in a certain range? A: One method is something like (int)((double)rand() / ((double)RAND_MAX + 1) * N) 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.

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: Try using the higher-order bits: see question 13.16.

13.20: How can I generate random numbers with a normal or Gaussian distribution? A: See the longer versions of this list for ideas.

13.24: I'm trying to port this old program. Why do I get "undefined external" errors for some library functions? A: Some semistandard functions have been renamed or replaced over the years; see the full list for details.

13.25: I get errors due to library functions being undefined even though I #include the right header files. A: You may have to explicitly ask for the correct libraries to be searched.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

13.26: I'm still getting errors due to library functions being undefined, even though I'm requesting the right libraries. A: Library search order is significant; usually, you must search the libraries last.

13.28: What does it mean when the linker says that _end is undefined? A: You generally get that message only when other symbols are undefined, too.

Section 14. Floating Point 14.1: When I set a float variable to 3.1, why is printf printing it as 3.0999999? Most computers use base 2 for floating-point numbers, and many fractions (including 0.1 decimal) are not exactly representable in base 2. Why is sqrt(144.) giving me crazy numbers? Make sure that you have #included <math.h>, and correctly declared other functions returning double. I keep getting "undefined: sin" compilation errors. Make sure you're actually linking with the math library. My floating-point calculations are acting strangely and giving me different answers on different machines. First, see question 14.2 above. If the problem isn't that simple, see the full list for a brief explanation, or any good programming book for a better one.

A:

14.2: A:

14.3: A: 14.4:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

14.5:

What's a good way to check for "close enough" floating-point equality? The best way is to use an accuracy threshold which is relative to the magnitude of the numbers being compared. How do I round numbers? For positive numbers, try (int)(x + 0.5) . Where is C's exponentiation operator? Try using the pow() function. The predefined constant M_PI seems to be missing from <math.h>. That constant is not standard. How do I test for IEEE NaN and other special values? There is not yet a portable way, but see the full list for ideas.

A:

14.6: A: 14.7: A: 14.8: A: 14.9: A:

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.

14.12: I'm looking for some mathematical library code. A: See Ajay Shah's index of free numerical software at ftp://ftp.math.psu.edu/pub/FAQ/numcomp-free-c .

14.13: I'm having trouble with a Turbo C program which crashes and says something like "floating point formats not linked." A: You may have to insert a dummy call to a floating-point library function to force loading of floating-point support.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Section 15. Variable-Length Argument Lists 15.1: I heard that you have to #include <stdio.h> before calling printf(). Why? So that a proper prototype for printf() will be in scope. How can %f be used for both float and double arguments in printf()? In variable-length argument lists, types char and short int are promoted to int, and float is promoted to double. Why don't function prototypes guard against mismatches in printf's arguments? Function prototypes do not provide any information about the number and types of variable arguments. How can I write a function that takes a variable number of arguments? Use the <stdarg.h> header. 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? Use vprintf(), vfprintf(), or vsprintf(). How can I write a function analogous to scanf(), that calls scanf() to do most of the work? C9X will support vscanf(). I have a pre-ANSI compiler, without <stdarg.h>. What can I do?

A: 15.2:

A:

15.3:

A:

15.4:

A: 15.5:

A: 15.6:

A: 15.7:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

There's an older header, <varargs.h>, which offers about the same functionality. How can I discover how many arguments a function was actually called with? Any function which takes a variable number of arguments must be able to determine *from the arguments' values* how many of them there are. My compiler isn't letting me declare a function that accepts *only* variable arguments. Standard C requires at least one fixed argument.

15.8:

A:

15.9:

A:

15.10: Why isn't "va_arg(argp, float)" working? A: Because the "default argument promotions" apply in variablelength argument lists, you should always use va_arg(argp, double).

15.11: I can't get va_arg() to pull in an argument of type pointer-tofunction. A: Use a typedef.

15.12: How can I write a function which takes a variable number of arguments and passes them to some other function ? A: In general, you cannot.

15.13: How can I call a function with an argument list built up at run time? A: You can't.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

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 preprocessing directives.

16.1c: Why isn't my procedure call working? A: 16.3: A: Function calls always require parenthesized argument lists. This program crashes before it even runs! Look for very large, local arrays. (See also questions 11.12b, 16.4, 16.5, and 18.4.) I have a program that seems to run correctly, but then crashes as it's exiting. See the full list for ideas. This program runs perfectly on one machine, but I get weird results on another. See the full list for a brief list of possibilities. Why does the code "char *p = "hello, world!"; p[0] = 'H';" crash? String literals are not modifiable, except (in effect) when they are used as array initializers. What does "Segmentation violation" mean? It generally means that your program tried to access memory it shouldn't have, invariably as a result of stack corruption or

16.4:

A: 16.5:

A: 16.6:

A:

16.8: A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

improper pointer use.

Section 17. Style 17.1: A: What's the best style for code layout in C? There is no one "best style," but see the full list for a few suggestions. Is the code "if(!strcmp(s1, s2))" good style? Not particularly. Why do some people write if(0 == x) instead of if(x == 0)? It's a trick to guard against the common error of writing if(x = 0) . I came across some code that puts a (void) cast before each call to printf(). Why? To suppress warnings about otherwise discarded return values. What is "Hungarian Notation"? It's a naming convention which encodes information about a variable's type in its name. Where can I get the "Indian Hill Style Guide" and other coding standards? See the unabridged list.

17.3: A: 17.4: A:

17.5:

A: 17.8: A:

17.9:

A:

17.10: Some people say that goto's are evil and that I should never use them. Isn't that a bit extreme? A: Yes. Absolute rules are an imperfect approach to good

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

programming style.

Section 18. Tools and Resources 18.1: I'm looking for C development tools (cross-reference generators, code beautifiers, etc.). See the full list for a few names. How can I track down these pesky malloc problems? See the full list for a list of tools. What's a free or cheap C compiler I can use? See the full list for a brief catalog. I just typed in this program, and it's acting strangely. you see anything wrong with it? See if you can run lint first. How can I shut off the "warning: possible pointer alignment problem" message which lint gives me for each call to malloc()? It may be easier simply to ignore the message, perhaps in an automated way with grep -v. Where can I get an ANSI-compatible lint? See the unabridged list for two commercial products. Don't ANSI function prototypes render lint obsolete? No. A good compiler may match most of lint's diagnostics; few provide all. Can

A: 18.2: A: 18.3: A: 18.4:

A: 18.5:

A:

18.7: A: 18.8: A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

18.9: A:

Are there any C tutorials or other resources on the net? There are several of them.

18.10: What's a good book for learning C? A: There are far too many books on C to list here; the full list contains a few pointers.

18.13: Where can I find the sources of the standard C libraries? A: Several possibilites are listed in the full list.

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: Several available packages are mentioned in the full list.

18.15: Where can I get a BNF or YACC grammar for C? A: See the ANSI Standard, or the unabridged list.

18.15b: Does anyone have a C compiler test suite I can use? A: See the full list for several sources.

18.15c: Where are some collections of useful code fragments and examples?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

See the full list for a few sources.

18.15d: I need code for performing multiple precision arithmetic. A: See the full list for a few ideas.

18.16: Where and how can I get copies of all these freely distributable programs? A: See the regular postings in the comp.sources.unix and comp.sources.misc newsgroups, or the full version of this list, for information.

Section 19. System Dependencies 19.1: How can I read a single character from the keyboard without waiting for the RETURN key? Alas, there is no standard or portable way to do this sort of thing in C. How can I find out how many characters are available for reading, or do a non-blocking read? These, too, are entirely operating-system-specific. How can I display a percentage-done indication that updates itself in place, or show one of those "twirling baton" progress indicators? The character '\r' is a carriage return, and '\b' is a backspace. How can I clear the screen, or print text in color, or move the cursor? The only halfway-portable solution is the curses library.

A:

19.2:

A: 19.3:

A:

19.4:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

19.5: A:

How do I read the arrow keys?

What about function keys?

Such things depend on the keyboard, operating system, and library you're using. How do I read the mouse? What system are you using? How can I do serial ("comm") port I/O? It's system-dependent. How can I direct output to the printer? See the full list for ideas. How do I send escape sequences to control a terminal or other device? By sending them. ESC is '\033' in ASCII.

19.6: A: 19.7: A: 19.8: A: 19.9:

A:

19.10: How can I do graphics? A: There is no portable way.

19.11: How can I check whether a file exists? A: You can try the access() or stat() functions. Otherwise, the only guaranteed and portable way is to try opening the file.

19.12: How can I find out the size of a file, prior to reading it in? A: You might be able to get an estimate using stat() or fseek/ftell (but see the full list for caveats).

19.12b: How can I find the modification date of a file?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Try stat().

19.13: How can a file be shortened in-place without completely clearing or rewriting it? A: There are various ways to do this, but there is no portable solution.

19.14: How can I insert or delete a line in the middle of a file? A: Short of rewriting the file, you probably can't.

19.15: How can I recover the file name given an open file descriptor? A: This problem is, in general, insoluble. It is best to remember the names of files yourself as you open them

19.16: How can I delete a file? A: The Standard C Library function is remove().

19.16b: How do I copy files? A: Open the source and destination files and copy a character or block at a time, or see question 19.27.

19.17: What's wrong with the call fopen("c:\newdir\file.dat", "r")? A: You probably need to double those backslashes.

19.18: How can I increase the allowable number of simultaneously open files? A: Check your system documentation.

19.20: How can I read a directory in a C program?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

See if you can use the opendir() and readdir() functions.

19.22: How can I find out how much memory is available? A: Your operating system may provide a routine which returns this information.

19.23: How can I allocate arrays or structures bigger than 64K? A: Some operating systems won't let you.

19.24: What does the error message "DGROUP exceeds 64K" mean? A: It means that you have too much static data.

19.25: How can I access memory located at a certain address? A: Set a pointer to the absolute address.

19.27: How can I invoke another program from within a C program? A: Use system().

19.30: How can I invoke another program and trap its output? A: Unix and some other systems provide a popen() function.

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. You may be able to duplicate the command language interpreter's search path logic to locate the executable.

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.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

19.33: How can a process change an environment variable in its caller? A: If it's possible to do so at all, it's system dependent.

19.36: How can I read in an object file and jump to locations in it? A: You want a dynamic linker or loader.

19.37: How can I implement a delay, or time a user's response, with subsecond resolution? A: Unfortunately, there is no portable way.

19.38: How can I trap or ignore keyboard interrupts like control-C? A: Use signal().

19.39: How can I handle floating-point exceptions gracefully? A: Take a look at matherr() and signal(SIGFPE). Do networking? Write client/server

19.40: How do I... Use sockets? applications? A:

These questions have more to do with the networking facilities you have available than they do with C. Use BIOS calls? Write ISR's? Create TSR's?

19.40b: How do I... A:

These are very particular to a particular system.

19.40c: I'm trying to compile a program in which "union REGS" and int86() are undefined. A: Those have to do with MS-DOS interrupt programming.

19.41: But I can't use all these nonstandard, system-dependent

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

functions, because my program has to be ANSI compatible! A: That's an impossible requirement. Any real program requires at least a few services which ANSI doesn't define.

Section 20. Miscellaneous 20.1: A: How can I return multiple values from a function? Either pass pointers to several locations which the function can fill in, or have the function return a structure containing the desired values. How do I access command-line arguments? Via main()'s argv parameter. How can I write data files which can be read on other machines with different data formats? The most portable solution is to use text files. How can I call a function, given its name as a string? The most straightforward thing to do is to maintain a correspondence table of names and function pointers. How can I implement sets or arrays of bits? Use arrays of char or int, with a few macros to access the desired bit at the proper index. How can I determine whether a machine's byte order is big-endian or little-endian? The usual tricks involve pointers or unions.

20.3: A: 20.5:

A: 20.6: A:

20.8: A:

20.9:

A:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

20.10: How can I convert integers to binary or hexadecimal? A: Internally, integers are already in binary. be able to select a base. During I/O, you may

20.11: Can I use base-2 constants (something like 0b101010)? Is there a printf() format for binary? A: No, on both counts.

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.

20.13: What's the best way of making my program efficient? A: By picking good algorithms and implementing them carefully. How much do function

20.14: Are pointers really faster than arrays? calls slow things down? A:

Precise answers to these and many similar questions depend on the processor and compiler in use.

20.15b: People claim that optimizing compilers are good, but mine can't even replace i/=2 with a shift. A: Was i signed or unsigned?

20.15c: How can I swap two values without using a temporary? A: The "clever" trick is a ^= b; b ^= a; a ^= b; see also question 3.3b.

20.17: Is there a way to switch on strings?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A:

Not directly.

20.18: Is there a way to have non-constant case labels (i.e. ranges or arbitrary expressions)? A: No.

20.19: Are the outer parentheses in return statements really optional? A: Yes. Are they legal inside quoted

20.20: Why don't C comments nest? strings? A:

C comments don't nest because PL/I's comments don't either. The character sequences /* and */ are not special within doublequoted strings.

20.20b: What does a+++++b mean ? A: Nothing. parsed. It's interpreted as "a ++ ++ + b", and cannot be

20.24: Why doesn't C have nested functions? A: They were deliberately left out of C as a simplification.

20.24b: What is assert()? A: It is a macro which documents an assumption being made by the programmer; it terminates the program if the assumption is violated.

20.25: How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions from C? A: The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

20.26: Does anyone know of a program for converting Pascal or FORTRAN to C? A: Several freely distributable programs are available, namely ptoc, p2c, and f2c. See the full list for details.

20.27: Can I use a C++ compiler to compile C code? A: Not necessarily; C++ is not a strict superset of C.

20.28: I need to compare two strings for close, but not necessarily exact, equality. A: See the full list for ideas.

20.29: What is hashing? A: A mapping of strings (or other data structures) to integers, for easier searching.

20.31: How can I find the day of the week given the date? A: Use mktime(), Zeller's congruence, or some code in the full list.

20.32: Will 2000 be a leap year? A: Yes.

20.34: How do you write a program which produces its own source code as output? A: Here's one: char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}"; main(){printf(s,34,s,34);}

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

20.35: What is "Duff's Device"? A: It's a devastatingly deviously unrolled byte-copying loop. the full list for details. See

20.36: When will the next Obfuscated C Code Contest be held? How can I get a copy of previous winning entries? A: See the full list, or http://www.ioccc.org/index.html .

20.37: What was the entry keyword mentioned in K&R1? A: It was reserved to allow functions with multiple, differentlynamed entry points, but it has been withdrawn.

20.38: Where does the name "C" come from, anyway? A: C was derived from B, which was inspired by BCPL, which was a simplification of CPL.

20.39: How do you pronounce "char"? A: Like the English words "char," "care," or "car" (your choice).

20.39b: What do "lvalue" and "rvalue" mean? A: An "lvalue" denotes an object that has a location; an "rvalue" is any expression that has a value.

20.40: Where can I get extra copies of this list? 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; the unabridged version is normally posted on the first of each month, with an Expires: line which should keep it around all month. It is 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

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(directory pub/usenet), and ftp.uu.net (directory usenet). A hypertext version of this FAQ list is available at http://www.eskimo.com/~scs/C-faq/top.html . An extended version has been published by Addison-Wesley as _C Programming FAQs: Frequently Asked Questions_ (ISBN 0-201-84519-9). Steve Summit scs@eskimo.com

This article is Copyright 1990-1999 by Steve Summit. Content from the book _C Programming FAQs: Frequently Asked Questions_ is made available here by permission of the author and the publisher as a service to the community. It is intended to complement the use of the published text and is protected by international copyright laws. The content is made available here and may be accessed freely for personal use but may not be republished without permission. [ By Archive-name | By Author | By Category | By Newsgroup ] [ Home | Latest Updates | Archive Stats | Search | Usenet References | Help ]

Send corrections/additions to the FAQ Maintainer: scs@eskimo.com


Last Update April 03 2002 @ 09:26 PM

Frequently Asked Questions - comp.lang.objective-c


compiled by David Stes (stes@pandora.be)November 9, 2000

Contents

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Contents 1. About this FAQ o 1.1 Where can I find the latest version of the FAQ ? 2. Objective-C Compiler Commands o 2.1 What's the file suffix for Objective-C source ? o 2.2 How do I compile .m files with the Stepstone compiler ? o 2.3 How do I compile .m files with the Apple compiler ? o 2.4 How do I compile .m files with the GNU C compiler ? o 2.5 How do I compile .m files with the POC ? 3. Objective-C preprocessor issues o 3.1 What's the syntax for comments ? o 3.2 How do I include the root class ? o 3.3 What is #import ? o 3.4 Why am I lectured about using #import ? 4. Object datatype (id) o 4.1 What is id ? o 4.2 What is the difference between self and super ? o 4.3 What is @defs() ? 5. Message selectors (SEL) o 5.1 What is a SEL ? o 5.2 What is perform: doing ? o 5.3 How do I know the SEL of a given method ? 6. Implementation pointers (IMP) o 6.1 What is an IMP ? o 6.2 How do I get an IMP given a SEL ? o 6.3 How do I send a message given an IMP ? o 6.4 How can I use IMP for methods returning double ? o 6.5 Can I use perform: for a message returning double ? 7. Copying objects o 7.1 What's the difference between copy and deepCopy ? 8. Objective-C and C++

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

o 8.1 How can I link a C++ library into an Objective-C program ? 9. Messages o 9.1 How do I make a static method ? o 9.2 How do I prevent an object from sending a given message ? o 9.3 Do I have to recompile everything if I change the implementation of a method ? 10. Instance and Class Variables o 10.1 Do I have to recompile everything if I change instance variables of a class ? 11. Objective-C and X-Windows o 11.1 How do I include X Intrinsics headers into an Objective-C file ? 12. Stepstone Specific Questions o 12.1 How do I allocate an object on the stack ? 13. GNU Objective-C Specific Questions o 13.1 Why do I get a 'floating point exception' ? 14. Apple Objective-C Specific Questions o 14.1 What's the class of a constant string ? o 14.2 How can I link a C++ library into an Objective-C program ? 15. Portable Object Compiler Objective-C Specific Questions o 15.1 What's the syntax for class variables ? o 15.2 How do I forward messages ? o 15.3 How can I link a C++ library into an Objective-C program ? 16. Books and further reading o 16.1 Object-Oriented Programming : An Evolutionary Approach, 2nd Ed. o 16.2 An Introduction To Object-Oriented Programming, 2nd Ed. o 16.3 Objective-C : Object-Oriented Programming Techniques o 16.4 Applications of Object-Oriented Programming; C++ SmallTalk Actor Objective-C Object PASCAL

1. About this FAQ


1.1 Where can I find the latest version of the FAQ ?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

It's posted once a month to comp.lang.objective-c, comp.answers and news.answers. It is archived at ftp://rtfm.mit.edu/pub/faqs/computer-lang/Objective-C/faq.

2. Objective-C Compiler Commands


2.1 What's the file suffix for Objective-C source ?
It's .m for implementation files, and .h for header files. Objective-C compilers usually also accept .c as a suffix, but compile those files in plain C mode.

2.2 How do I compile .m files with the Stepstone compiler ?


objcc -c class.m objcc -o class class.o

See http://www.stepstn.com for more information.

2.3 How do I compile .m files with the Apple compiler ?


cc -c class.m cc -o class class.o

See http://www.apple.com for more information.

2.4 How do I compile .m files with the GNU C compiler ?


gcc -c class.m gcc -o class class.o -lobjc -lpthread

See http://www.gnu.org for more information.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

2.5 How do I compile .m files with the POC ?


objc -c class.m objc -o class class.o

See http://metalab.unc.edu/pub/Linux/devel/lang/objc/ for more information.

3. Objective-C preprocessor issues


3.1 What's the syntax for comments ?
The Objective-C preprocessor usually supports two styles of comments :
// this is a BCPL-style comment (extends to end of line)

and
/* this is a C-style comment */

3.2 How do I include the root class ?


On Stepstone and the POC, the header file to include is :
<Object.h>

On GNU cc and Apple cc, it's :


<objc/Object.h>

The root class is located in a directory called runtime for the Stepstone compiler, and in a directory called objcrt for the POC, but because of implicit -I options passed on to the preprocessor, these locations are automatically searched.

3.3 What is #import ?


It's a C preprocessor construct to avoid multiple inclusions of the same file.
#import <Object.h>

is an alternative to

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#include <Object.h> where the .h file is protected #ifndef _OBJECT_H_ ... #define _OBJECT_H_ #endif

itself against multiple inclusions :

3.4 Why am I lectured about using #import ?


The GNU Objective-C compiler emits a warning when you use #import because some people find using #import poor style. You can turn off the warning by using the -Wno-import option, you could modify the compiler source code and set the variable warn_import (in the file cccp.c) or you could convert your code to use pairs of #ifndef and #endif, as shown above, which makes your code work with all compilers.

4. Object datatype (id)


4.1 What is id ?
It's a generic C type that Objective-C uses for an arbitrary object. For example, a static function that takes one object as argument and returns an object, could be declared as :
static id myfunction(id argument) { ... }

4.2 What is the difference between self and super ?


is a variable that refers to the object that received a message in a method implementation. super refers to the same variable, but directs the compiler to use a method implementation from the superclass. Using pseudo-code, where copy (from super) is the syntax for the copy implementation of the superclass, the following are equivalent :
self myObject = [super copy];

and,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

myObject = [self copy (from super)]; // pseudo-code

4.3 What is @defs() ?


It's a compiler directive to get access to the internal memory layout of instances of a particular class.
typedef struct { @defs(MyClass) } *TMyClass; defines a C-type TMyClass with a memory layout that is

the same as that of MyClass instances.

5. Message selectors (SEL)


5.1 What is a SEL ?
It's the C type of a message selector; it's often defined as a (uniqued) string of characters (the name of the method, including colons), but not all compilers define the type as such.

5.2 What is perform: doing ?


perform:

is a message to send a message, identified by its message selector (SEL), to an object.

5.3 How do I know the SEL of a given method ?


If the name of the method is known at compile time, use @selector :
[myObject perform:@selector(close)];

At runtime, you can lookup the selector by a runtime function that takes the name of the message as argument, as in :
SEL SEL SEL SEL mySel mySel mySel mySel = = = = selUid(name); // for Stepstone sel_getUid(name); // for Apple sel_get_any_uid(name); // for GNU Objective C selUid(name); // for POC

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

6. Implementation pointers (IMP)


6.1 What is an IMP ?
It's the C type of a method implementation pointer, a function pointer to the function that implements an Objective-C method. It is defined to return id and takes two hidden arguments, self and _cmd :
typedef id (*IMP)(id self,SEL _cmd,...);

6.2 How do I get an IMP given a SEL ?


This can be done by sending a methodFor: message :
IMP myImp = [myObject methodFor:mySel];

6.3 How do I send a message given an IMP ?


By dereferencing the function pointer. The following are all equivalent :
[myObject myMessage];

or
IMP myImp = [myObject methodFor:@selector(myMessage)]; myImp(myObject,@selector(myMessage));

or
[myObject perform:@selector(myMessage)];

6.4 How can I use IMP for methods returning double ?


For methods that return a C type such as double instead of id, the IMP function pointer is casted from pointer to a function returning id to pointer to a function returning double :
double aDouble = ((double (*) (id,SEL))myImp)(self,_cmd);

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

6.5 Can I use perform: for a message returning double ?


No. The method perform: is for sending messages returning id without any other argument. Use perform:with: if the message returns id and takes one argument. Use methodFor: for the general case of any number of arguments and any return type.

7. Copying objects
7.1 What's the difference between copy and deepCopy ?
is intented to make a bytecopy of the object, sharing pointers with the original, and can be overridden to copy additional memory. deepCopy is intented to make a copy that doesn't share pointers with the original. A deep copy of an object contains copies of its instance variables, while a plain copy is normally just a copy at the first level.
copy

8. Objective-C and C++


8.1 How can I link a C++ library into an Objective-C program ?
You have two options : either use the Apple compiler or use the POC. The former accepts a mix of C++ and Objective-C syntax (called Objective-C++), the latter compiles Objective-C into C and then compiles the intermediate code with a C++ compiler. See the compiler specific questions for more information.

9. Messages
9.1 How do I make a static method ?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Methods are always implemented in Objective-C as static functions. The only way to obtain the IMP (implementation pointer) of a method is through the runtime (via methodFor: and friends), because the function itself is static to the file that implements the method.

9.2 How do I prevent an object from sending a given message ?


You can't. If your object responds to a message, any other class can send this message. You could add an extra argument sender and check, as in :
- mymethod:sender { if ([sender isKindOf:..]) ... }

But this still requires cooperation of the sender, to use a correct argument :
[anObject mymethod:self];

9.3 Do I have to recompile everything if I change the implementation of a method ?


No, you only have to recompile the implementation of the method itself. Files that only send that particular messages do not have to be recompiled because Objective-C has dynamic binding.

10. Instance and Class Variables


10.1 Do I have to recompile everything if I change instance variables of a class ?
You have to recompile that class, all of its subclasses, and those files that use @defs() or use direct access to the instance variables of that class. In short, using @defs() to access instance variables, or accessing instance variables through subclassing, breaks the encapsulation that the Objective-C runtime normally provides for all other files (the files that you do not have to recompile).

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

11. Objective-C and X-Windows


11.1 How do I include X Intrinsics headers into an Objective-C file ?
To avoid a conflict between Objective-C's Object and the X11/Object, do the following :
#include <Object.h> #define Object XtObject #include <X11/Intrinsic.h> #include <X11/IntrinsicP.h> #undef Object

12. Stepstone Specific Questions


12.1 How do I allocate an object on the stack ?
To allocate an instance of 'MyClass' on the stack :
MyClass aClass = [MyClass new];

13. GNU Objective-C Specific Questions


13.1 Why do I get a 'floating point exception' ?
This used to happen on some platforms and is described at ftp://ftp.ics.ele.tue.nl/pub/users/tiggr/objc/README.387. A solution was to add -lieee to the command line, so that an invalid floating point operation in the runtime did not send a signal. DJGPP users can consult http://www.delorie.com/djgpp/v2faq/. AIX users may want to consult http://world.std.com/

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

~gsk/oc-rs6000-problems.html. In some cases, you can fix the problem by upgrading to a more recent version of the GNU ObjectiveC runtime and/or compiler.

14. Apple Objective-C Specific Questions


14.1 What's the class of a constant string ?
It's an NXConstantString.
NXConstantString *myString = @"my string";

14.2 How can I link a C++ library into an Objective-C program ?


c++ -c file.m c++ file.o -lcpluslib -o myprogram

15. Portable Object Compiler Objective-C Specific Questions


15.1 What's the syntax for class variables ?
List the class variables after the instance variables, and group them together in the same way as instance variables, as follows :
@implementation MyClass : Object { id ivar1; int ivar2; } : { id cvar1; } @end

15.2 How do I forward messages ?


You have to implement doesNotUnderstand: to send a sentTo: message.
- doesNotUnderstand:aMsg {

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

return [aMsg sentTo:aProxy]; }

15.3 How can I link a C++ library into an Objective-C program ?


objc -c -cplus file.m objc -cplus file.o -lcpluslib -o myprogram

16. Books and further reading


16.1 Object-Oriented Programming : An Evolutionary Approach, 2nd Ed.
Brad Cox & Andy Novobilski, ISBN 0201548348.

16.2 An Introduction To Object-Oriented Programming, 2nd Ed.


Timothy Budd, ISBN 0201824191

16.3 Objective-C : Object-Oriented Programming Techniques


Pinson, Lewis J. / Wiener, Richard S., ISBN 0201508281

16.4 Applications of Object-Oriented Programming; C++ SmallTalk Actor Objective-C Object PASCAL
Pinson, Lewis J. / Wiener, Richard S., ISBN 0201503697

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

[alt.comp.lang.learn.c-c++] - FAQ list


Message-ID: <C-faq/learn_973504065@rtfm.mit.edu> Supersedes: <C-faq/learn_970824110@rtfm.mit.edu> Expires: 20 Dec 2000 09:47:45 GMT X-Last-Updated: 1999/08/26 Organization: none From: Sunil Rao <sunil.rao@ic.ac.uk> Newsgroups: alt.comp.lang.learn.cc++,comp.lang.c,comp.lang.c++,comp.lang.c.moderated,alt.answers,comp.answers,news.answers Followup-To: poster Organisation: ISE @ ic.ac.uk Subject: [alt.comp.lang.learn.c-c++] - FAQ list Summary: This post contains useful information for anyone wishing to learn C and C++, listing online tutorials and resources, giving book recommendations and helping clear some common misconceptions. Date: 06 Nov 2000 09:49:59 GMT X-Trace: dreaderd 973504199 5711 18.181.0.29 Archive-name: C-faq/learn Posting-Frequency: monthly Last-modified: 23 August 1999 URL: http://www.raos.demon.co.uk/acllc-c++/faq.html This document is a FAQ list for the newsgroup alt.comp.lang.learn.c-c++. It provides readers with a framework and a set of guidelines for posting here, in addition to answering a number of questions newcomers here tend to ask. This FAQ is meant to be read in its entirety. It is posted monthly to alt.comp.lang.learn.c-c++, comp.lang.c, comp.lang.c++, comp.lang.c.moderated, comp.answers, alt.answers and news.answers.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

This is the plaintext version of this list. An HTML version can be located at http://www.raos.demon.co.uk/acllc-c++/faq.html

Compiled by Sunil Rao <sunil.rao@ic.ac.uk>. Comments, suggestions, corrections, constructive criticism and requests for clarification will be gratefully acknowledged.

Last update: 23 August 1999 Last changes made: Updated and expanded the answers to questions 6, 10, 15, 16, 17, 18 and 19. To do list: To add answers to a number of questions and to update information regarding compilers.

Special Thanks to... Dennis Swanson, Jim Gewin, Billy Chambless, Mark Brown, Dave Dunfield, Jack Klein, Steve Summit, Steve Clamage, Dennis Ritchie, Kaz Kylheku, Lars Hecking, Pablo Halpern, Jerry Coffin, Stuart Hall, Dann Corbit, Michael McGoldrick, Cameron Foster, Brody Hurst, Jabari Adisa, Wieland Stbinger, Chris Newton and Bernd Luevelsmeyer for their helpful comments, suggestions, advice, corrections and constructive criticism, and (in the case of some) for permitting me to quote from their papers/posts.

1: What is the purpose of this newsgroup? alt.comp.lang.learn.c-c++ is an unmoderated newsgroup for the discussion of issues that concern novice and non-expert programmers in C and C++ who wish to *LEARN* more about one or both of these languages.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

That probably looks scary. Basically, anybody can post to the group. Provided the questions you post are on-topic and the answers you provide are accurate, you should not have a problem. If your question is off-topic, you will typically be redirected to a newsgroup that is more appropriate; if your answers are inaccurate, you risk being corrected with a flame.

2: What is C/C++? First of all, C and C++ are different languages. C was created by Dennis Ritchie as an efficient language for systems programming. Bjarne Stroustrup then extended C by adding features to support object-oriented programming. C++ can be considered to be a superset of C, but there are real differences between them. It can usually (though not always) be assumed that anybody who talks about "C/C++" as one language is no expert - this extends to book authors too. It is normally unclear whether somebody is referring to "C OR C++" or "C AND C++" when using this expression, so it is probably best avoided.

3: So, are C and C++ not so similar after all? They are indeed similar to a great extent. Incompatibilities do exist, though, and many idiomatic constructs used in C are frowned upon by C++ experts. C++ programmers generally consider code that does not exploit those features of C++ that make it possible to write better programs - programs that are more readable and easier to write and maintain - to be in poor style. The differences between the two languages are significant enough to ensure that one has to be clear about the language being used. However, it must not be forgotten that C++ is a largely a superset of C, and that it is possible (though perhaps not desirable) to write code that works correctly in both languages. A lot of people incorrectly believe that object-oriented

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

programs cannot be written in C; this is not true. What is true is that C++ provides features that make it easier to write in a style that is object-oriented; in other words, C++ supports programming in an object-oriented style.

4: What is the difference between this newsgroup and comp.lang.c or comp.lang.c++? This newsgroup is primarily intended for discussion related to the LEARNING of C and C++. The other two groups are primarily intended for discussion of the features of the respective languages themselves. Naturally, some overlap does occur. This group does tend to be slightly (perhaps excessively so) more informal, though. Most regulars on this group show great patience with many common beginners' questions and will willingly expound on many topics of interest or particular difficulty, referring to appropriate reference material, either in printed or in electronic form, as necessary.

5: What kind of questions may be asked here? Any question relating to any aspect of C or C++ that you're having trouble understanding is on topic here. By C, what is meant is the language PROPER and its standard library as defined by ANSI and ISO. C++ discussions are about the proposed language standard (that recently passed its formal vote) and the library it defines. Any questions relating to specific compilers, third-party or nonstandard libraries, compiler extensions etc are unwelcome here, and will probably be answered with a redirection to a more appropriate newsgroup. If you've been thus redirected, do not get miffed or upset and post an angry response - it will cut no ice with the regulars and will only label you as an unwilling learner. What's discussed in this group is rigidly defined to limit the traffic and make the group useful to as wide a possible audience as possible.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

6: I have a burning question about XXX. What should I do first? First of all, do check to see if your question has not been been answered before. Look up any of the standard references on the language. If you can't find the answer, browse the group, lurk here for a few days, search the archives at Deja.com, read the relevant FAQs (including those of comp.lang.c and comp.lang.c++), and if you STILL can't find the answer, post by all means. Note that you might not be the first ever learner to have run into your problems. There is a good chance that your question has been answered before. Deja.com: http://www.deja.com/ C FAQ: http://www.eskimo.com/~scs/C-faq/top.html C++ FAQ: http://www.cerfnet.com/~mpcline/c++-faq-lite/

7: What other points should I make note of BEFORE posting here? Please observe basic Netiquette guidelines. If you're not sure of what these are, subscribe to news.announce.newusers, and read *ALL* of the posts there. A good reference is http://www.ezine.com/netiquette.html To summarise these points very briefly - ensure that your post is on topic. Do your homework before posting. Don't post the same question one hundred times. Don't troll. Don't post homework questions without anything to show your effort. Don't ask for replies to be sent by email. Don't post binaries. Make sure that your subject line is an accurate description of the problem/topic. Please do not ask for replies by email. If you haven't got the time or patience to read the newsgroup, that's tough. The answers you receive might benefit other readers of the newsgroup as well, and you yourself might learn more from the discussions your question

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

might generate. If you have to reply, be accurate and precise - your reply is being read by LEARNERS, remember. If you are unsure or have nothing new to add, don't bother. For heaven's sake, don't get abusive when you are corrected or redirected. If you are unsure as to why you have been redirected, ask the person who did so *PRIVATELY* by email. There usually is a good reason - see question 9. Do not take any answers on trust. Sadly, many of those who post answers here know even less than the interested learner who posted the original question. Wait for a few days before relying on any posted code or answers, just in case they might be corrected by others. This is also why it is a very bad idea to email your questions directly to regulars; you have no insurance against any potential mistakes - remember that nobody is infallible. Please do not make any MIME or UUENCODED posts (this includes HTML). Many newsreaders cannot handle such posts correctly. You will only make it impossible for many to read your posts. And please try not to flame. This is a learners' group. Not everyone who posts here is aware of all the issues involved. A grumpy attitude only makes things difficult for everyone concerned. It usually helps if you indicate in somewhere in your post if you're expecting a C or a C++ answer - several techniques appropriate to C++ will not work in C, and some C programs will not work or are considered bad style under C++. It also makes it easier for other readers - they can then safely ignore your post if they cannot help you with it. If you're not sure as to which language you're learning, you probably need to get better resources to learn from.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

8: I posted a homework question, but got no help; only sarcastic responses. Why? Homework questions are in general not welcome here - most attempts to disguise one usually do not work particularly well. You will typically receive no help unless you can demonstrate that you have made an honest attempt to solve the problem yourself, by posting some code you have trouble with, for instance. There is little point in a regular supplying you with code to fulfil an assignment if you are going to pass the course and come out and work on real-world projects without knowing how to even tackle a basic homework problem. See also http://home.att.net/~jackklein/ctips01.html#homework http://members.xoom.com/jshiva/hw.txt

9: Why are questions relating to Windows, Graphics, Sockets etc. offtopic here? Questions on these topics come up every so often here. C and C++ are languages, not operating systems. They come with limited, though highly useful, standard libraries. While any question relating to these libraries is relevant and most certainly on topic, a question relating to MFCs, for instance, is of absolutely no interest to a Unix expert, and vice-versa. There exist newsgroups DEVOTED to these non-standard additions. It certainly makes more sense to post a question in a place where there is a greater chance of it being answered, and answered correctly. As a beginner, it probably makes more sense to concentrate on the core language itself and master that before branching off to learn system-specific tricks. See also http://members.xoom.com/jshiva/offtopic.txt

10: What are some other related groups where I might post questions?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(Answer adapted from the regular "Welcome to comp.lang.c" post by Billy Chambless and Tim Behrendsen) You *really* ought to be able to work out where to post by yourself. Please, please, please, for heavens' sake read the FAQs and lurk for a while before posting your questions. Please do not post to more groups than are necessary. Think carefully about the relevance of your post before you post to any of the newsgroups mentioned below. If you decide that your question is indeed relevant to more than one newsgroup and is not a FAQ, please cross-post rather than multi-post. Remember that many regular readers of this newsgroup also follow several of the other groups mentioned below. Note: if your news server does not carry the borland, microsoft or watcom newsgroups, you might find it necessary to connect to forums.borland.com, msnews.microsoft.com or forums.sybase.com instead. See also http://www.borland.com/newsgroups/ http://sdn.sybase.com/sdn/appdev/newsgroups.stm * Language Issues C C++ x86 assembly comp.lang.c, comp.lang.c.moderated comp.lang.c++.moderated, comp.lang.c++ comp.lang.asm.x86

* Non-language-specific Issues Algorithms Graphics comp.programming comp.graphics.algorithms

Another avenue worth exploring for general algorithms questions might be the bulletin board at the Analysis of Algorithms homepage based at http://pauillac.inria.fr/algo/AofA/ and mirrored at http://www.cecm.sfu.ca/mirror/INRIA/algo/AofA/.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

There is a real difference between an algorithm and an implementation thereof. A question regarding an algorithm itself is, strictly speaking, off-topic though issues do get raised here in the absence of any good newsgroup to discuss them in. Questions relating to implementations are of course on-topic here. * Compilers/Libraries The gcc compiler DJGPP (gcc for DOS) Borland C++ Borland C++Builder Visual C++ Watcom C/C++ CodeWarrior MFC OWL VCL gnu.gcc comp.os.msdos.djgpp borland.public.cpp borland.public.cpp.language borland.public.cppbuilder borland.public.cppbuilder.language microsoft.public.vc.ide_general microsoft.public.vc.language powersoft.public.watcom_c_c++.general comp.sys.mac.programmer.codewarrior microsoft.public.vc.mfc comp.os.ms-windows.programmer.tools.mfc borland.public.cpp.owl comp.os.ms-windows.programmer.tools.owl borland.public.cppbuilder.vcl

* Operating Systems/System Specifics DOS issues MS Windows comp.os.msdos.programmer comp.os.ms-windows.programmer.misc microsoft.public.win16.programmer.* microsoft.public.win32.programmer.* comp.os.os2.programmer.misc comp.sys.mac.programmer.misc comp.unix.programmer comp.sys.amiga.programmer

OS/2 Macintosh General UNIX Amiga

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

11: HELP! My program does not work correctly. What do I do now? Before posting code here, try and make sure that it at least compiles correctly, even if it does not quite behave the way you intended it to. Try and localise your error to a particular function or section of code - most readers have no time to wade through pages of code (If you are unable to do this, you probably need to start again from scratch anyway.). Do NOT under any circumstances post all of your code as an attachment - many will simply ignore your post. Please also specify if your code is C or C++. Essentially, post the smallest complete program that manifests the problem. This makes it easier for the reader to answer your question. You might find that doing this enables you to answer your question yourself! Read the answer to the above question as well. And do learn how to use the debugger that came with your compiler. It usually helps if you set the warning levels to the highest possible for your compiler - let the compiler pick out any errors and warn you of any potential problems. And if you post any errors or warning messages with your code, it makes it that much easier for a regular to see what's wrong with your code - any need to compile it yet again will be minimised, especially if the error is a common one.

12: What online tutorials exist for learning C and C++? The best online tutorial for C I have come across has got to be Steve Summit's class notes for the C courses he teaches. http://www.eskimo.com/~scs/cclass/cclass.html There are references to other C tutorials in his C FAQ as well. Vinit Carpenter maintains a list of resources for learning C and C++. Do note, however, that a fair number of the tutorials

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

placed online contain mistakes and/or are out of date. http://www.cyberdiem.com/vin/learn.html Ted Jensen's tutorial on pointers and arrays in C can be found at http://pweb.netcom.com/~tjensen/ptr/cpoint.htm Tom Torfs has written an excellent, complete tutorial, meant to complement a good introduction to C. It's not primarily intended for the complete beginner to the language, though. http://members.xoom.com/tomtorfs/cintro.html See also the answer to question 18.

13: What should I look for when picking a book to learn from? Opinions vary widely. Most readers learnt from, regardless of whether suitable for the learner. The fact books are either full of errors or even both!) makes matters worse. recommend the book(s) they or not they might actually be that many commonly recommended hopelessly out of date (or

Beware of books that claim to teach you both C and C++ - they might end up teaching you a horrible hybrid instead. It is also probably better to stick to books that conform to the C and C++ standards, at least while beginning. Many compiler-specific books do not go into sufficient depth regarding important language issues and usually fail to be clear as to whether something is specific to the compiler under consideration or not. Some texts come bundled with compilers - it's usually worth checking to see how out-of-date the compiler actually is. For C, this is probably less of an issue than it is for C++, simply because compiler writers have had over a decade to catch up with the standard. It pays to keep more than one good book handy; many books known for their technical accuracy can seem dense and unreadable in places,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

and you might at times need to back up a primer with a reference. Do make sure that you get the latest edition of any of these books you decide to purchase. Also please check to see if there is an errata list available online for any book you decide on; this is particularly important for programming language texts. It pays to be suspicious of books for which such lists cannot be located online for whatever reason. The Association of C and C++ Users maintains a collection of book reviews taken from its journals. Many of the reviews are fair and excellent in their criticism, though there are a few minor inconsistencies and a number of truly awful books have escaped with favourable reviews. It's a useful starting-point, though. http://www.accu.org/bookreviews/public/ Many C and C++ experts recommend against using ANY book written by a certain Herbert Schildt. To see why, read the answer to question 16. The "Dummies" series of books is not particularly well-regarded either in general.

14: What are the best books I can learn C from? If you wish to learn C, the classic text - the "Bible" - is "The C Programming Language", 2nd Edition, by Brian Kernighan and Dennis Ritchie. This hallowed text describes and explains ANSI C. K&R2 is renowned for its brevity, clarity, elegance and completeness; but these very factors can make it heavy going for the beginner. http://cm.bell-labs.com/cm/cs/cbook/ K N King's "C Programming: A Modern Approach" is another text frequently recommended on comp.lang.c. This book is a good, thorough introduction to C that is a lot easier to work with from a beginner's perspective. http://knking.com/books/c/ Another frequently recommended book on C is "C - How to

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Program", 2nd Edition, by H M Deitel and P J Deitel. Please note that I have not had a chance to read this book, and include the reference on the strength of the the recommendation of a number of regular posters to comp.lang.c. http://www.deitel.com/products_and_services/publications/chtp2.htm

15: What are the best books I can learn C++ from? Before going further, I should mention that I am not a C++ programmer myself, and the recommendations listed here are based on positive comments I have heard from others. The C++ equivalent of K&R2 is "The C++ Programming Language", 3rd Edition, by Bjarne Stroustrup. Experienced C++ programmers love it; however, many beginners seem to find it very hard going indeed. Like K&R2, it assumes basic familiarity with programming concepts and is not really intended for the absolute beginner. It does not assume any previous knowledge of C. http://www.research.att.com/~bs/about_3rd.html A more accessible book that is intended for beginners is "C++ Primer", 3rd Edition, by Stanley Lippman and Jose Lajoie. This book is thorough, and conforms to the C++ standard. It is reportedly extremely clear and detailed, and, again, does not assume any previous knowledge of C. http://cseng.aw.com/bookdetail.qry?ISBN=0-201-82470-1&ptype=0 Another text I've seen seen particularly recommended is "C++ - How to Program", 2nd Edition, by H M Deitel and P J Deitel. Again, this text does not assume prior knowledge of C. http://www.deitel.com/products_and_services/publications /cpphtp2.htm Other texts I have newsgroups include Yourself C++ in 21 Stephen Prata, and seen recommended a number of times on the C++ the badly-named-though-often-recommended "Teach days" by Jesse Liberty, "C++ Primer Plus" by "Thinking in C++" by Bruce Eckel.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

http://www.libertyassociates.com/book_edit.htm#21 Days http://www.bruceeckel.com/books.html#ThinkingInCPlusPlus Bruce Eckel has also placed a "beta" of the second edition of his "Thinking in C++" online as well. Do remember that it isn't the final version and that there might remain some as-yet undetected errors. http://www.eckelobjects.com/ThinkingInCPP2e.html The C++ FAQ contains some recommendations for C++ books as well.

16: Why do many experts not think very highly of Herbert Schildt's books? A good answer to this question could fill a book by itself. While no book is perfect, Schildt's books, in the opinion of many gurus, seem to positively aim to mislead learners and encourage bad habits. Schildt's beautifully clear writing style only makes things worse by causing many "satisfied" learners to recommend his books to other learners. Do take a look at the following scathing articles before deciding to buy a Schildt text. http://www.lysator.liu.se/c/schildt.html http://herd.plethora.net/~seebs/c/c_tcr.html The above reviews are admittedly based on two of Schildt's older books. However, the language they describe has not changed in the intervening period, and several books written at around the same time remain highly regarded. The following humorous post also illustrates the general feeling towards Schildt and his books. http://www.qnx.com/~glen/deadbeef/2764.html There is exactly one and ONLY one C book bearing Schildt's name on its cover that is at all recommended by many C experts - see Q 25.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

17: Where can I get a free C or C++ compiler? (Answer adapted from Joe Buck's FAQ for g++ and libg++.) * gcc gcc is a free C and C++ compiler from the Free Software Foundation available for many Unix-based systems. Its ports for other systems are also freely available. http://www.fsf.org/software/gcc/gcc.html ftp://prep.ai.mit.edu/pub/gnu/ egcs (the experimental gnu compiler system) is another free project (based on gcc). Check out http://www.cygnus.com/egcs/ The MS-DOS port (DJGPP) of gcc runs on a 386 or higher, and is a full 32-bit compiler. Make sure you read the FAQ thoroughly first, however, and post any questions you have regarding its setup to comp.os.msdos.djgpp, not here. http://www.delorie.com/djgpp/ For a port of gcc that works on 32-bit Windows, look at http://www.cygnus.com/misc/gnu-win32/ Also, for another port, see http://www.xraylith.wisc.edu/~khan/software/ gnu-win32/egcs-mingw32.html You could also get hold of Bloodshed Dev-C++, which is essentially Mingw32 bundled with an editor, packaged in an easier-to-use form. http://www.bloodshed.nu/devc.html For the Amiga, BeOS, and pOS, look at the GG port of gcc at http://www.ninemoons.com/GG/

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

EMX is a port of gcc to OS/2 that also works on DOS. http://www.os2ss.com/unix/emx09c/

* lcc lcc-win32 is a free C compiler available for 32-bit Windows. http://www.cs.virginia.edu/~lcc-win32/ It is based on the retargettable lcc system. http://www.cs.princeton.edu/software/lcc/

* Pacific C The Pacific C compiler is available for free for personal use. You can download it from http://www.hitech.com.au/products/pacific.html

* MPW If you're programming under the Apple Macintosh, you can obtain the Macintosh Programmers' workshop for free. http://developer.apple.com/tools/mpw-tools/

* Turbo C Inprise (formerly known as Borland) have commenced making older versions of their software available for free download. This includes older (possibly pre-standard) versions of their Turbo C compiler. http://community.borland.com/museum/

* Micro-C

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

If you are looking for a free C compiler for MS-DOS that is easy to install and use, take a look at Micro-C, available from http://www.dunfield.com/ Do bear in mind that it is not wholly compatible with the standard. The incompatibilites are well-documented, however.

18: What good websites/online references exist for C and C++? http://www.lysator.liu.se/c/ is an excellent resource for C, containing a number of extremely useful links and pointers. For beginners to C (and C++), Jack Klein has put up an excellent page with tips, suggestions and expanded answers to a number of commonly asked beginners' questions. http://home.att.net/~jackklein/c/c_main.html The Comeau Computing web site features several highly informative and useful resource pages, including http://www.comeaucomputing.com/resources/litsuggs.html http://www.comeaucomputing.com/faqs/cppfaq.html Steve Summit has archived some of his longer and more informative Usenet posts at http://www.eskimo.com/~scs/readings/index2.html Check out the C++ Virtual Library for some useful C++ links. http://www.desy.de/user/projects/C++.html You may wish to look at the C Language Online Journal at http://www.cs.wustl.edu/~jxh/CLOJ/ For some useful code snippets (some portable; others not), check out Bob Stout's SNIPPETS archive at http://www.snippets.org/ Karim Ratib's well-indexed code page has links to many useful

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

resources. http://www.iro.umontreal.ca/~ratib/code Martin Leslie's C Programming reference site is at http://www.gator.net/~garyg/C/c.html Jamie Blustein's C Programming Language resources are at http://www.csd.uwo.ca/~jamie/.Refs/C-refs.html Scott McMahan's C Programmer's Notebook, which discusses a number of issues C programmers encounter as their experience grows, is at http://www.skwc.com/essent/prognotebook.html Some questions relating to what standard C is all about are answered at http://lglwww.epfl.ch/~wolf/c/ Also, check out The Mining Company's C/C++ site, http://cplus.miningco.com/ Jon Morris Smith's C++ resources directory, http://www.cs.bham.ac.uk/~jdm/cpp.html Robert Davies' list of online C++ references, http://nz.com/webnz/robert/cpp_site.html The #C++ site, http://www.cl.ais.net/morph/c++/main.html and Simo Salminen's Programmers' Oasis C and C++ page. http://www.utu.fi/~sisasa/oasis/oasis-cc++.html

19: Should I learn C before learning C++?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

According to a number of C++ experts, including its creator Bjarne Stroustrup, and Marshall Cline (the author of the C++ FAQ), the answer is a firm no. Look up the C++ FAQ to see why Cline thinks you do not need to learn C before C++. A post by Bjarne Stroustrup to comp.lang.c++ addresses this point too. http://www.research.att.com/~bs/learn.html "Learning Standard C++ as a New Language" - a paper by Stroustrup available from http://www.research.att.com/~bs/papers.html examines this much-debated issue in great depth, but the paper is aimed more at educators than at beginners.

20: What is the difference between C++ and Visual C++? C++ is a programming language. Visual C++ is Microsoft's implementation of it. When people talk about learning Visual C++, it usually has more to do with learning how to use the programming environment, and how to use the Microsoft Foundation Classes (MFCs) for Windows rather than any language issues. Visual C++ can and will compile straight C and C++.

21: What is portability? Why are so many people concerned about it? C and C++ are languages that are not tied down to a particular platform. This means that, with care, it is possible to write useful code in either of these languages that will run on different platforms without modification. That is not to say that ALL code written in these languages must conform strictly to the standards - in practice it is sometimes neither possible nor desirable to achieve this aim. However, the job of porting code is made easier when any system-specific stuff is carefully packaged or abstracted away, so that it is clear and straightforward to make the necessary changes during a port.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

In order to be able to do this effectively, it is important to be aware of what can and can not be done within the realms of the standards set by these languages. That is why a lot of importance is placed on adhering strictly to the standards, at least while learning.

22: How do I BEGIN to write C or C++ under Visual or Borland C++? This question is, strictly speaking, off-topic, but is answered here since it's one that seems to plague many beginners. To start with, you need to make sure that you are not writing a Windows application. Try creating a new project or application to target MS-DOS, QuickWin or Win32 Console depending on your compiler version. You can then use the Standard C and C++ libraries to write strictly conforming programs. It's best to learn to write standard-conforming programs first before branching off into writing Windows programs. If you find that you are having a lot of trouble setting up your compiler, a good place to ask questions is a newsgroup devoted to your compiler. See Question 10 for a list of such groups.

23: HELP! My program seems to compile correctly, but when it runs, a DOS window flashes and then vanishes. This can sometimes occur when you are developing programs using an IDE. A command prompt window opens and displays the output, and control is passed back immediately to the IDE. To get around this, you can look through the various menus to find a "View Output Screen" option. Alternatively, you could open a command prompt window and change directory to the one your executable is going to end up in and run your executable directly from there.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The solution of using a non-standard function to keep the executable running until a key is pressed is not a very good idea especially if you are going to run your program outside of the development environment.

24: Why doesn't this FAQ cover language issues? This is because other better, more comprehensive resources exist for this purpose. See the answers to questions 12 and 18.

25: Where can I obtain a copy of the standards for C and C++? You cannot obtain copies of the standards for free. This is because the standards organisations earn a large part of their revenue from selling printed copies. The C FAQ tells you how you can obtain copies of the C standard. You could also buy "The Annotated ANSI C Standard", by the afore-mentioned Herbert Schildt (question 16). Make sure that you ignore the annotations completely, however. The C++ standard can be obtained online directly from the ANSI Electronic Standards store . After registering yourself for free, you can download the document in Adobe PDF format on payment of $18.00 (US) by credit card. http://webstore.ansi.org/ansidocstore/default.asp The standards documents can be daunting at first sight; meant, as they are, to be as formal and precise as possible. They are NOT suitable for learning from, but are intended rather to be used as the ultimate authority to check with on any language issue. Also, check the comp.std.c++ FAQ. http://reality.sgi.com/austern_mti/std-c++/faq.html

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

26: HELP! I get errors when I try to compile "hello, world"! Check your source to make sure you haven't missed any semi-colons or braces. Also remember that C and C++ are case-sensitive - Main() and main() are completely different, for instance. If you are satisfied that the program source is all right, then you probably have not set your compiler up properly. You might need to ask one of the experts in a newsgroup devoted to your compiler about this see the answer to question 10. The sole reason for redirecting compiler setup questions to other groups is to reinforce the point that a language is inherently separate from an implementation of one. There are simply too many different implementations of C and C++, and too many subtleties involved in the actual learning of C and C++ for all of them to come under the banner of this newsgroup.

27: Which language should I learn first then - C or C++? The answer to this depends on your own inclinations. C is a smaller, less complex language than C++, and is consequently easier to master. However, it is probably easier to get up to speed with C++, if you make effective use of the standard library. Some find C to be more elegant than C++, others think it to be too "unsafe". C++ programmers generally feel that it has features that make it easier to write good, robust, readable and maintainable code in than in C. If you do decide to learn C++, there is little point in learning C itself first. See also question 19. If you have little or no programming experience, be prepared to face a real challenge. C and C++ have enough quirks and subtleties to catch out even expert programmers in other languages. It's not impossible to learn to program with C or C++ as a first language, just more difficult than with Turing, Pascal or a structured

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

BASIC, for instance. Programming in C or in C++ is generally considered to be a more pleasureable experience than doing so in beginners' languages by those experienced in either, but the very fact that your freedom is limited and restricted by these languages makes them easier to learn.

28: Why are C and C++ so popular and widely-used? (First part of answer adapted from a March 1998 comp.lang.c post by Kaz Kylheku on "Why Has C Proved To Be Such A Succesful Language") C has always been a language that never attempts to tie a programmer down - it allows for easy implementation, it comes with a genuinely useful standard library that can itself be implemented in C, and it is both efficient and portable. C has always appealed to systems programmers who like the terse, concise manner in which powerful expressions can be coded. C was widely distributed with an Operating System (Unix) that was actually largely written in C itself. Also, C allowed programmers to (while sacrificing portability) have direct access to many machine-level features that would otherwise require the use of Assembly Language. As Dennis Ritchie writes in his paper, "The Development of the C Language", C is quirky, flawed, and an enormous success. While accidents of history surely helped, it evidently satisfied a need for a system implementation language efficient enough to displace assembly language, yet sufficiently abstract and fluent to describe algorithms and interactions in a wide variety of environments. C++ has its basis in C - extending it by supporting features meant to encourage and support the development of large programs. Perhaps most importantly, it supports object-oriented programming in a familiar setting and framework (that of C). When C++ was created,

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

one of the initial aims was to retain compatibility with C to as large an extent as possible, and retain its spirit and efficiency. It was possible to convert from C to C++ gradually, thus making use of C++ (initally, at least) as a "better C", and moving on to using other features. This allowed many C programmers to learn C++ quickly (though using C++ effectively requires a major mind-shift for many C programmers).

29: Why is this FAQ so grumpy/terse/curt/unfriendly? A lot of questions posted in alt.comp.lang.learn.c-c++ are posted by people who are generally unsure about what they are learning. Many beginners fail to appreciate that C and C++ are used on a number of platforms, and that what works with a particular compiler is not necessarily going to work with another, even on the same platform. It is important that a learner be clear about the differences between programming in standard C or C++, and programming using platform- and compiler-specific extensions. In the long run, this approach - that of separating the idea of "language" and "platform" - leads to a better understanding of both the language and the platform. It is generally accepted that the sooner this is appreciated by the learner, the better. Usenet style in general tends to be terse and to-the-point and this FAQ reflects that, while attempting to be as fully informative as possible. This is the only reason for grumpiness - most interested learners find alt.comp.lang.learn.c-c++ a very pleasant and helpful place once they understand this. The newsgroup is nowhere near as grumpy as this FAQ might suggest - certainly not towards someone who has read and understood all it has to say! -{ Sunil Rao } "...certainly no beast has essayed the boundless, infinitely inventive art of human hatred. No beast can match its range and power." - Arundhati Roy, "The God of Small Things", 1997.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

[ By Archive-name | By Author | By Category | By Newsgroup ] [ Home | Latest Updates | Archive Stats | Search | Usenet References | Help ]

Send corrections/additions to the FAQ Maintainer: Sunil Rao <sunil.rao@ic.ac.uk>


Last Update April 03 2002 @ 09:27 PM

comp.lang.c FAQ list Table of Contents


From: scs@eskimo.com (Steve Summit) Newsgroups: comp.lang.c,comp.lang.c.moderated,comp.answers,news.answers Subject: comp.lang.c FAQ list Table of Contents Followup-To: poster Date: 1 Mar 2002 11:00:22 GMT Organization: only when absolutely necessary Expires: 3 Apr 2002 00:00:00 GMT Message-ID: <2002Mar01.0600.scs.0003@eskimo.com> Reply-To: scs@eskimo.com X-Trace: eskinews.eskimo.com 1014980422 11543 204.122.16.13 (1 Mar 2002 11:00:22 GMT) X-Complaints-To: abuse@eskimo.com NNTP-Posting-Date: 1 Mar 2002 11:00:22 GMT Summary: questions only (answers elsewhere) X-Last-Modified: February 7, 1999 X-Archive-Name: C-faq/toc X-Version: 3.5 X-URL: http://www.eskimo.com/~scs/C-faq/top.html X-PGP-Signature: Version: 2.6.2 iQCSAwUBNr5tYt6sm4I1rmP1AQG/YgPmNVdryv5rqXPD0kRCvo/XJWUTRsg7f/JL OmwQ7AuopSEsyrUCM02hSdJtA8lRG5pfcCaeXKynyPHDRrDVqNSuboaas+aqP/DW K47h/xrC4LkLQtc77lcYscwwhRoREmn6GzbrCRczcRK/lWf+1LWKUE6eu/XX7wFW aXwwfMU= =J/uc Archive-name: C-faq/toc

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Comp-lang-c-archive-name: C-FAQ-list.toc URL: http://www.eskimo.com/~scs/C-faq/top.html [Last modified February 7, 1999 by scs.] This article is questions (FAQ) versions of the wordings of the list.) a table of contents for the comp.lang.c frequently-asked list, listing the questions which the abridged and full FAQ list answer. (Both lists answer all questions; the questions in this article are taken from the abridged

If you have only just come across this article, you will naturally be wondering where the lists which it indexes can be found. The unabridged version is normally posted to comp.lang.c on the first of each month, and the abridged version twice per month, both with Expires: lines which should keep them around all month. They can also be found in the newsgroups comp.answers and news.answers . They are available for anonymous ftp from ftp.eskimo.com in directoru u/s/scs/C-faq/. Several sites archive news.answers postings and other FAQ lists, including comp.lang.c's: 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/ ). A web version is at http://www.eskimo.com/~scs/C-faq/top.html . See the meta-FAQ list in news.answers for more information. Section Section Section Section Section Section Section Section Section Section Section Section Section 1. Declarations and Initializations 2. Structures, Unions, and Enumerations 3. Expressions 4. Pointers 5. Null Pointers 6. Arrays and Pointers 7. Memory Allocation 8. Characters and Strings 9. Boolean Expressions and Variables 10. C Preprocessor 11. ANSI/ISO Standard C 12. Stdio 13. Library Functions

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Section Section Section Section Section Section Section

14. 15. 16. 17. 18. 19. 20.

Floating Point Variable-Length Argument Lists Strange Problems Style Tools and Resources System Dependencies Miscellaneous Bibliography Acknowledgements

Section 1. Declarations and Initializations 1.1: 1.4: 1.7: 1.11: 1.12: 1.14: How do you decide which integer type to use? What should the 64-bit type on a machine that can support it? What's the best way to declare and define global variables? What does extern mean in a function declaration? What's the auto keyword good for? I can't seem to define a linked list node which contains a pointer to itself. 1.21: How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters? 1.22: How can I declare a function that returns a pointer to a function of its own type? 1.25: My compiler is complaining about an invalid redeclaration of a function, but I only define it once. 1.25b: What's the right declaration for main()? 1.30: What am I allowed to assume about the initial values of variables which are not explicitly initialized? 1.31: Why can't I initialize a local array with a string? 1.31b: What's wrong with "char *p = malloc(10);" ? 1.32: What is the difference between char a[] = "string"; and char *p = "string"; ? 1.34: How do I initialize a pointer to a function?

Section 2. Structures, Unions, and Enumerations

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

2.1: 2.2: 2.3: 2.4: 2.6:

2.7: 2.8: 2.10: 2.11: 2.12: 2.13: 2.14: 2.15: 2.18: 2.20: 2.22: 2.24:

What's the difference between struct x1 { ... }; and typedef struct { ... } x2; ? Why doesn't "struct x { ... }; x thestruct;" work? Can a structure contain a pointer to itself? What's the best way of implementing opaque (abstract) data types in C? I came across some code that declared a structure with the last member an array of one element, and then did some tricky allocation to make it act like the array had several elements. Is this legal or portable? I heard that structures could be assigned to variables and passed to and from functions, but K&R1 says not. Is there a way to compare structures automatically? Can I pass constant values to functions which accept structure arguments? How can I read/write structures from/to data files? How can I turn off structure padding? Why does sizeof report a larger size than I expect for a structure type? How can I determine the byte offset of a field within a structure? How can I access structure fields by name at run time? I have a program which works correctly, but dumps core after it finishes. Why? Can I initialize unions? What is the difference between an enumeration and a set of preprocessor #defines? Is there an easy way to print enumeration values symbolically?

Section 3. Expressions 3.1: 3.2: Why doesn't the code "a[i] = i++;" work? Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++);" prints 49. Regardless of the order of evaluation, shouldn't it print 56? What should the code "int i = 3; i = i++;" do? Here's a slick expression: "a ^= b ^= a ^= b". It swaps a and b

3.3: 3.3b:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

3.4: 3.5: 3.8: 3.9: 3.12: 3.14: 3.16:

without using a temporary. Don't precedence and parentheses dictate order of evaluation? But what about the && and || operators? What's a "sequence point"? So given a[i] = i++; we don't know which cell of a[] gets written to, but i does get incremented by one, right? If I'm not using the value of the expression, should I use i++ or ++i to increment a variable? Why doesn't the code "int a = 1000, b = 1000; long int c = a * b;" work? Can I use ?: on the left-hand side of an assignment expression?

Section 4. Pointers 4.2: 4.3: 4.5: 4.8: 4.9: 4.10: 4.11: 4.12: What's wrong with "char *p; *p = malloc(10);"? Does *p++ increment p, or what it points to? I want to use a char * pointer to step over some ints. Why doesn't "((int *)p)++;" work? I have a function which accepts, and is supposed to initialize, a pointer, but the pointer in the caller remains unchanged. Can I use a void ** pointer as a parameter so that a function can accept a generic pointer by reference? I have a function which accepts a pointer to an int. How can I pass a constant like 5 to it? Does C even have "pass by reference"? I've seen different methods used for calling functions via pointers.

Section 5. Null Pointers 5.1: 5.2: 5.3: 5.4: 5.5: What is this infamous null pointer, anyway? How do I get a null pointer in my programs? Is the abbreviated pointer comparison "if(p)" to test for nonnull pointers valid? What is NULL and how is it #defined? How should NULL be defined on a machine which uses a nonzero bit

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

5.6: 5.9: 5.10: 5.12: 5.13: 5.14: 5.15: 5.16:

5.17: 5.20:

pattern as the internal representation of a null pointer? If NULL were defined as "((char *)0)," wouldn't that make function calls which pass an uncast NULL work? If NULL and 0 are equivalent as null pointer constants, which should I use? But wouldn't it be better to use NULL, in case the value of NULL changes? I use the preprocessor macro "#define Nullptr(type) (type *)0" to help me build null pointers of the correct type. This is strange. NULL is guaranteed to be 0, but the null pointer is not? Why is there so much confusion surrounding null pointers? I'm confused. I just can't understand all this null pointer stuff. Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes? Seriously, have any actual machines really used nonzero null pointers? What does a run-time "null pointer assignment" error mean?

Section 6. Arrays and Pointers 6.1: 6.2: 6.3: 6.4: 6.7: 6.8: 6.9: 6.11: 6.12: I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn't it work? But I heard that char a[] was identical to char *a. So what is meant by the "equivalence of pointers and arrays" in C? Why are array and pointer declarations interchangeable as function formal parameters? How can an array be an lvalue, if you can't assign to it? What is the real difference between arrays and pointers? Someone explained to me that arrays were really just constant pointers. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C? What's the difference between array and &array?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

6.13: 6.14: 6.15: 6.16: 6.17: 6.18: 6.19: 6.20:

6.21:

How do I declare a pointer to an array? How can I set an array's size at run time? How can I declare local arrays of a size matching a passed-in array? How can I dynamically allocate a multidimensional array? Can I simulate a non-0-based array with a pointer? My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer. How do I write functions which accept two-dimensional arrays when the width is not known at compile time? How can I use statically- and dynamically-allocated multidimensional arrays interchangeably when passing them to functions? Why doesn't sizeof properly report the size of an array which is a parameter to a function?

Section 7. Memory Allocation 7.1: 7.2: 7.3: 7.3b: 7.3c: 7.5a: 7.5b: 7.6: 7.7: 7.8: 7.14: Why doesn't the code "char *answer; gets(answer);" work? I can't get strcat() to work. I tried "char *s3 = strcat(s1, s2);" but I got strange results. But the man page for strcat() says that it takes two char *'s as arguments. How am I supposed to know to allocate things? I just tried the code "char *p; strcpy(p, "abc");" and it worked. Why didn't it crash? How much memory does a pointer variable allocate? I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage. So what's the right way to return a string? Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to malloc()? Why does some code carefully cast the values returned by malloc to the pointer type being allocated? Why does so much code leave out the multiplication by sizeof(char) when allocating strings? I've heard that some operating systems don't actually allocate malloc'ed memory until the program tries to use it. Is this

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

7.16: 7.17: 7.19: 7.20: 7.21: 7.22: 7.23: 7.24: 7.25: 7.26: 7.27: 7.30: 7.31: 7.32:

legal? I'm allocating a large array for some numeric work, but malloc() is acting strangely. I've got 8 meg of memory in my PC. Why can I only seem to malloc 640K or so? My program is crashing, apparently somewhere down inside malloc. You can't use dynamically-allocated memory after you free it, can you? Why isn't a pointer null after calling free()? When I call malloc() to allocate memory for a local pointer, do I have to explicitly free() it? When I free a dynamically-allocated structure containing pointers, do I also have to free each subsidiary pointer? Must I free allocated memory before the program exits? Why doesn't my program's memory usage go down when I free memory? How does free() know how many bytes to free? So can I query the malloc package to find out how big an allocated block is? Is it legal to pass a null pointer as the first argument to realloc()? What's the difference between calloc() and malloc()? What is alloca() and why is its use discouraged?

Section 8. Characters and Strings 8.1: 8.2: 8.3: 8.6: 8.9: Why doesn't "strcat(string, '!');" work? Why won't the test if(string == "value") correctly compare string against the value? Why can't I assign strings to character arrays? How can I get the numeric (character set) value corresponding to a character? Why is sizeof('a') not 1?

Section 9. Boolean Expressions and Variables

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

9.1: 9.2: 9.3:

What is the right type to use for Boolean values in C? What if a built-in logical or relational operator "returns" something other than 1? Is if(p), where p is a pointer, valid?

Section 10. C Preprocessor 10.2: I've got some cute preprocessor macros that let me write C code that looks more like Pascal. What do y'all think? 10.3: How can I write a generic macro to swap two values? 10.4: What's the best way to write a multi-statement macro? 10.6: What are .h files and what should I put in them? 10.7: Is it acceptable for one header file to #include another? 10.8a: What's the difference between #include <> and #include "" ? 10.8b: What are the complete rules for header file searching? 10.9: I'm getting strange syntax errors on the very first declaration in a file, but it looks fine. 10.10b: I'm #including the header file for a function, but the linker keeps saying it's undefined. 10.11: Where can I get a copy of a missing header file? 10.12: How can I construct preprocessor #if expressions which compare strings? 10.13: Does the sizeof operator work in preprocessor #if directives? 10.14: Can I use an #ifdef in a #define line, to define something two different ways? 10.15: Is there anything like an #ifdef for typedefs? 10.16: How can I use a preprocessor #if expression to detect endianness? 10.18: How can I preprocess some code to remove selected conditional compilations, without preprocessing everything? 10.19: How can I list all of the predefined identifiers? 10.20: I have some old code that tries to construct identifiers with a macro like "#define Paste(a, b) a/**/b", but it doesn't work any more. 10.22: What does the message "warning: macro replacement within a string literal" mean? 10.23-4: I'm having trouble using macro arguments inside string

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

literals, using the `#' operator. 10.25: I've got this tricky preprocessing I want to do and I can't figure out a way to do it. 10.26: How can I write a macro which takes a variable number of arguments?

Section 11. ANSI/ISO Standard C 11.1: 11.2: 11.2b: 11.3: 11.4: 11.5: 11.8: 11.9: 11.10: 11.12a: 11.12b: 11.13: 11.14: 11.15: 11.16: 11.17: 11.18: 11.19: What is the "ANSI C Standard?" How can I get a copy of the Standard? Where can I get information about updates to the Standard? My ANSI compiler is complaining about prototype mismatches for parameters declared float. Can you mix old-style and new-style function syntax? Why does the declaration "extern int f(struct x *p);" give me a warning message? Why can't I use const values in initializers and array dimensions? What's the difference between "const char *p" and "char * const p"? Why can't I pass a char ** to a function which expects a const char **? What's the correct declaration of main()? Can I declare main() as void, to shut off these annoying "main returns no value" messages? But what about main's third argument, envp? I believe that declaring void main() can't fail, since I'm calling exit() instead of returning. The book I've been using always uses void main(). Is exit(status) truly equivalent to returning the same status from main()? How do I get the ANSI "stringizing" preprocessing operator `#' to stringize the macro's value instead of its name? What does the message "warning: macro replacement within a string literal" mean? I'm getting strange syntax errors inside lines I've #ifdeffed out.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

11.20: 11.21: 11.22: 11.24: 11.25: 11.26: 11.27: 11.29: 11.30: 11.31: 11.32: 11.33: 11.34: 11.35:

What are #pragmas ? What does "#pragma once" mean? Is char a[3] = "abc"; legal? Why can't I perform arithmetic on a void * pointer? What's the difference between memcpy() and memmove()? What should malloc(0) do? Why does the ANSI Standard not guarantee more than six caseinsensitive characters of external identifier significance? My compiler is rejecting the simplest possible test programs, with all kinds of syntax errors. Why are some ANSI/ISO Standard library functions showing up as undefined, even though I've got an ANSI compiler? Does anyone have a tool for converting old-style C programs to ANSI C, or for automatically generating prototypes? Why won't frobozz-cc, which claims to be ANSI compliant, accept this code? What's the difference between implementation-defined, unspecified, and undefined behavior? I'm appalled that the ANSI Standard leaves so many issues undefined. I just tried some allegedly-undefined code on an ANSI-conforming compiler, and got the results I expected.

Section 12. Stdio 12.1: What's wrong with the code "char c; while((c = getchar()) != EOF) ..."? 12.2: Why won't the code "while(!feof(infp)) { fgets(buf, MAXLINE, infp); fputs(buf, outfp); }" work? 12.4: My program's prompts and intermediate output don't always show up on the screen. 12.5: How can I read one character at a time, without waiting for the RETURN key? 12.6: How can I print a '%' character with printf? 12.9: How can printf() use %f for type double, if scanf() requires %lf? 12.9b: What printf format should I use for a typedef when I don't know

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

12.10: 12.11: 12.12: 12.13: 12.15: 12.17: 12.18:

12.19: 12.20: 12.21:

12.23: 12.24: 12.25: 12.26: 12.30: 12.33: 12.34: 12.36b: 12.38:

the underlying type? How can I implement a variable field width with printf? How can I print numbers with commas separating the thousands? Why doesn't the call scanf("%d", i) work? Why doesn't the code "double d; scanf("%f", &d);" work? How can I specify a variable width in a scanf() format string? When I read numbers from the keyboard with scanf "%d\n", it seems to hang until I type one extra line of input. 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()! I'm re-prompting the user if scanf() fails, but sometimes it seems to go into an infinite loop. Why does everyone say not to use scanf()? What should I use instead? 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()? Why does everyone say not to use gets()? Why does errno contain ENOTTY after a call to printf()? What's the difference between fgetpos/fsetpos and ftell/fseek? Will fflush(stdin) flush unread characters from the standard input stream? I'm trying to update a file in place, by using fopen mode "r+", but it's not working. How can I redirect stdin or stdout from within a program? Once I've used freopen(), how can I get the original stream back? How can I arrange to have output go two places at once? How can I read a binary data file properly?

Section 13. Library Functions 13.1: 13.2: 13.5: How can I convert numbers to strings? Why does strncpy() not always write a '\0'? Why do some versions of toupper() act strangely if given an upper-case letter?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

13.6: 13.7: 13.8: 13.9:

13.10: 13.11: 13.12: 13.13: 13.14: 13.14b: 13.15: 13.16: 13.17: 13.18: 13.20: 13.24: 13.25: 13.26: 13.28:

How can I split up a string into whitespace-separated fields? I need some code to do regular expression and wildcard matching. I'm trying to sort an array of strings with qsort(), using strcmp() as the comparison function, but it's not working. Now I'm trying to sort an array of structures, but the compiler is complaining that the function is of the wrong type for qsort(). How can I sort a linked list? How can I sort more data than will fit in memory? How can I get the time of day in a C program? How can I convert a struct tm or a string into a time_t? How can I perform calendar manipulations? Does C have any Year 2000 problems? I need a random number generator. How can I get random integers in a certain range? Each time I run my program, I get the same sequence of numbers back from rand(). I need a random true/false value, so I'm just taking rand() % 2, but it's alternating 0, 1, 0, 1, 0... How can I generate random numbers with a normal or Gaussian distribution? I'm trying to port this old program. Why do I get "undefined external" errors for some library functions? I get errors due to library functions being undefined even though I #include the right header files. I'm still getting errors due to library functions being undefined, even though I'm requesting the right libraries. What does it mean when the linker says that _end is undefined?

Section 14. Floating Point 14.1: 14.2: 14.3: 14.4: When I set a float variable to 3.1, why is printf printing it as 3.0999999? Why is sqrt(144.) giving me crazy numbers? I keep getting "undefined: sin" compilation errors. My floating-point calculations are acting strangely and giving me different answers on different machines.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

14.5:

What's a good way to check for "close enough" floating-point equality? 14.6: How do I round numbers? 14.7: Where is C's exponentiation operator? 14.8: The predefined constant M_PI seems to be missing from <math.h>. 14.9: How do I test for IEEE NaN and other special values? 14.11: What's a good way to implement complex numbers in C? 14.12: I'm looking for some mathematical library code. 14.13: I'm having trouble with a Turbo C program which crashes and says something like "floating point formats not linked."

Section 15. Variable-Length Argument Lists 15.1: 15.2: 15.3: 15.4: 15.5: I heard that you have to #include <stdio.h> before calling printf(). Why? How can %f be used for both float and double arguments in printf()? Why don't function prototypes guard against mismatches in printf's arguments? How can I write a function that takes a variable number of arguments? 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? How can I write a function analogous to scanf(), that calls scanf() to do most of the work? I have a pre-ANSI compiler, without <stdarg.h>. What can I do? How can I discover how many arguments a function was actually called with? My compiler isn't letting me declare a function that accepts *only* variable arguments. Why isn't "va_arg(argp, float)" working? I can't get va_arg() to pull in an argument of type pointer-tofunction. How can I write a function which takes a variable number of arguments and passes them to some other function ? How can I call a function with an argument list built up at run

15.6: 15.7: 15.8: 15.9: 15.10: 15.11: 15.12: 15.13:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

time?

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. 16.1c: Why isn't my procedure call working? 16.3: This program crashes before it even runs! 16.4: I have a program that seems to run correctly, but then crashes as it's exiting. 16.5: This program runs perfectly on one machine, but I get weird results on another. 16.6: Why does the code "char *p = "hello, world!"; p[0] = 'H';" crash? 16.8: What does "Segmentation violation" mean?

Section 17. Style 17.1: 17.3: 17.4: 17.5: What's the best style for code layout in C? Is the code "if(!strcmp(s1, s2))" good style? Why do some people write if(0 == x) instead of if(x == 0)? I came across some code that puts a (void) cast before each call to printf(). Why? 17.8: What is "Hungarian Notation"? 17.9: Where can I get the "Indian Hill Style Guide" and other coding standards? 17.10: Some people say that goto's are evil and that I should never use them. Isn't that a bit extreme?

Section 18. Tools and Resources 18.1: 18.2: I'm looking for C development tools (cross-reference generators, code beautifiers, etc.). How can I track down these pesky malloc problems?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

18.3: 18.4: 18.5: 18.7: 18.8: 18.9: 18.10: 18.13: 18.13b: 18.13c: 18.14: 18.15: 18.15b: 18.15c: 18.15d: 18.16:

What's a free or cheap C compiler I can use? I just typed in this program, and it's acting strangely. Can you see anything wrong with it? How can I shut off the "warning: possible pointer alignment problem" message which lint gives me for each call to malloc()? Where can I get an ANSI-compatible lint? Don't ANSI function prototypes render lint obsolete? Are there any C tutorials or other resources on the net? What's a good book for learning C? Where can I find the sources of the standard C libraries? Is there an on-line C reference manual? Where can I get a copy of the ANSI/ISO C Standard? I need code to parse and evaluate expressions. Where can I get a BNF or YACC grammar for C? Does anyone have a C compiler test suite I can use? Where are some collections of useful code fragments and examples? I need code for performing multiple precision arithmetic. Where and how can I get copies of all these freely distributable programs?

Section 19. System Dependencies 19.1: 19.2: 19.3: How can I read a single character from the keyboard without waiting for the RETURN key? How can I find out how many characters are available for reading, or do a non-blocking read? How can I display a percentage-done indication that updates itself in place, or show one of those "twirling baton" progress indicators? How can I clear the screen, or print text in color, or move the cursor? How do I read the arrow keys? What about function keys? How do I read the mouse? How can I do serial ("comm") port I/O? How can I direct output to the printer? How do I send escape sequences to control a terminal or other

19.4: 19.5: 19.6: 19.7: 19.8: 19.9:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

19.10: 19.11: 19.12: 19.12b: 19.13: 19.14: 19.15: 19.16: 19.16b: 19.17: 19.18: 19.20: 19.22: 19.23: 19.24: 19.25: 19.27: 19.30: 19.31: 19.32: 19.33: 19.36: 19.37: 19.38: 19.39: 19.40: 19.40b: 19.40c: 19.41:

device? How can I do graphics? How can I check whether a file exists? How can I find out the size of a file, prior to reading it in? How can I find the modification date of a file? How can a file be shortened in-place without completely clearing or rewriting it? How can I insert or delete a line in the middle of a file? How can I recover the file name given an open file descriptor? How can I delete a file? How do I copy files? What's wrong with the call fopen("c:\newdir\file.dat", "r")? How can I increase the allowable number of simultaneously open files? How can I read a directory in a C program? How can I find out how much memory is available? How can I allocate arrays or structures bigger than 64K? What does the error message "DGROUP exceeds 64K" mean? How can I access memory located at a certain address? How can I invoke another program from within a C program? How can I invoke another program and trap its output? How can my program discover the complete pathname to the executable from which it was invoked? How can I automatically locate a program's configuration files in the same directory as the executable? How can a process change an environment variable in its caller? How can I read in an object file and jump to locations in it? How can I implement a delay, or time a user's response, with subsecond resolution? How can I trap or ignore keyboard interrupts like control-C? How can I handle floating-point exceptions gracefully? How do I... Use sockets? Do networking? Write client/server applications? How do I... Use BIOS calls? Write ISR's? Create TSR's? I'm trying to compile a program in which "union REGS" and int86() are undefined. But I can't use all these nonstandard, system-dependent functions, because my program has to be ANSI compatible!

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Section 20. Miscellaneous 20.1: 20.3: 20.5: 20.6: 20.8: 20.9: 20.10: 20.11: 20.12: 20.13: 20.14: 20.15b: 20.15c: 20.17: 20.18: 20.19: 20.20: 20.20b: 20.24: 20.24b: 20.25: 20.26: 20.27: How can I return multiple values from a function? How do I access command-line arguments? How can I write data files which can be read on other machines with different data formats? How can I call a function, given its name as a string? How can I implement sets or arrays of bits? How can I determine whether a machine's byte order is big-endian or little-endian? How can I convert integers to binary or hexadecimal? Can I use base-2 constants (something like 0b101010)? Is there a printf() format for binary? What is the most efficient way to count the number of bits which are set in an integer? What's the best way of making my program efficient? Are pointers really faster than arrays? How much do function calls slow things down? People claim that optimizing compilers are good, but mine can't even replace i/=2 with a shift. How can I swap two values without using a temporary? Is there a way to switch on strings? Is there a way to have non-constant case labels (i.e. ranges or arbitrary expressions)? Are the outer parentheses in return statements really optional? Why don't C comments nest? Are they legal inside quoted strings? What does a+++++b mean ? Why doesn't C have nested functions? What is assert()? How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions from C? Does anyone know of a program for converting Pascal or FORTRAN to C? Is C++ a superset of C? Can I use a C++ compiler to compile C code?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

20.28: I need to compare two strings for close, but not necessarily exact, equality. 20.29: What is hashing? 20.31: How can I find the day of the week given the date? 20.32: Will 2000 be a leap year? 20.34: How do you write a program which produces its own source code as output? 20.35: What is "Duff's Device"? 20.36: When will the next Obfuscated C Code Contest be held? How can I get a copy of previous winning entries? 20.37: What was the entry keyword mentioned in K&R1? 20.38: Where does the name "C" come from, anyway? 20.39: How do you pronounce "char"? 20.39b: What do "lvalue" and "rvalue" mean? 20.40: Where can I get extra copies of this list? Steve Summit scs@eskimo.com

This article is Copyright 1990-1999 by Steve Summit. Content from the book _C Programming FAQs: Frequently Asked Questions_ is made available here by permission of the author and the publisher as a service to the community. It is intended to complement the use of the published text and is protected by international copyright laws. The content is made available here and may be accessed freely for personal use but may not be republished without permission. [ By Archive-name | By Author | By Category | By Newsgroup ] [ Home | Latest Updates | Archive Stats | Search | Usenet References | Help ]

Send corrections/additions to the FAQ Maintainer: scs@eskimo.com


Last Update April 03 2002 @ 09:27 PM

Question 6.1

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn't it work?

The declaration extern char *a simply does not match the actual definition. The type pointer-to-type-T is not the same as array-of-type-T. Use extern char a[]. References: ANSI Sec. 3.5.4.2 ISO Sec. 6.5.4.2 CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5

Question 6.2
But I heard that char a[] was identical to char *a.

Not at all. (What you heard has to do with formal parameters to functions; see question 6.4.) Arrays are not pointers. The array declaration char a[6] requests that space for six characters be set aside, to be known by the name ``a.'' That is, there is a location named ``a'' at which six characters can sit. The pointer declaration char *p, on the other hand, requests a place which holds a pointer, to be known by the name ``p.'' This pointer can point almost anywhere: to any char, or to any contiguous array of chars, or nowhere (see also questions 5.1 and 1.30). As usual, a picture is worth a thousand words. The declarations
char a[] = "hello";

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

char *p = "world";

would initialize data structures which could be represented like this:

+---+---+---+---+---+---+

a: | h | e | l | l | o |\0 |

+---+---+---+---+---+---+

+-----+

+---+---+---+---+---+---+

p: | *======> | w | o | r | l | d |\0 |

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

+-----+

+---+---+---+---+---+---+

It is important to realize that a reference like x

[3] generates different code depending on whether x is an array or a pointer. Given the declarations above, when the compiler sees the expression a[3], it emits code to start at the location ``a,'' move three past it, and fetch the character there. When it sees the expression p[3], it emits code to start at the location ``p,'' fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to. In other words, a[3] is three places past (the start of) the object named a, while p[3] is three places past the object pointed to by p. In the example above, both a[3] and p[3] happen to be the character 'l', but the compiler gets there differently.

References: K&R2 Sec. 5.5 p. 104 CT&P Sec. 4.5 pp. 64-5

Read sequentially: prev next up top

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.3

So what is meant by the ``equivalence of pointers and arrays'' in C?

Much of the confusion surrounding arrays and pointers in C can be traced to a misunderstanding of this statement. Saying that arrays and pointers are ``equivalent'' means neither that they are identical nor even interchangeable. ``Equivalence'' refers to the following key definition:

An lvalue of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T.

(The exceptions are when the array is the operand of a

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

sizeof or & operator, or is a string literal initializer for a character array.)

As a consequence of this definition, the compiler doesn't apply the array subscripting operator

[] that differently to arrays and pointers, after all. In an expression of the form a[i], the array decays into a pointer, following the rule above, and is then subscripted just as would be a pointer variable in the expression p[i] (although the eventual memory accesses will be different, as explained in question 6.2). If you were to assign the array's address to the pointer:

p = a;

then

p[3] and a[3] would access the same element.

See also question 6.8. References: K&R1 Sec. 5.3 pp. 93-6 K&R2 Sec. 5.3 p. 99 ANSI Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6 ISO Sec. 6.2.2.1, Sec. 6.3.2.1, Sec. 6.3.6 H&S Sec. 5.4.1 p. 124

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.4

Then why are array and pointer declarations interchangeable as function formal parameters?

It's supposed to be a convenience. Since arrays decay immediately into pointers, an array is never actually passed to a function. Allowing pointer parameters to be declared as arrays is a simply a way of making it

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

look as though the array was being passed--a programmer may wish to emphasize that a parameter is traditionally treated as if it were an array, or that an array (strictly speaking, the address) is traditionally passed. As a convenience, therefore, any parameter declarations which ``look like'' arrays, e.g. f(a) char a[]; { ... }

are treated by the compiler as if they were pointers, since that is what the function will receive if an array is passed:
f(a) char *a; { ... }

This conversion holds only within function formal parameter declarations, nowhere else. If the conversion bothers you, avoid it; many people have concluded that the confusion it causes outweighs the small advantage of having the declaration ``look like'' the call or the uses within the function.
See also question 6.21. References: K&R1 Sec. 5.3 p. 95, Sec. A10.1 p. 205 K&R2 Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226 ANSI Sec. 3.5.4.3, Sec. 3.7.1, Sec. 3.9.6 ISO Sec. 6.5.4.3, Sec. 6.7.1, Sec. 6.9.6 H&S Sec. 9.3 p. 271 CT&P Sec. 3.3 pp. 33-4

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.7

How can an array be an lvalue, if you can't assign to it?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The ANSI C Standard defines a ``modifiable lvalue,'' which an array is not.

References: ANSI Sec. 3.2.2.1

ISO Sec. 6.2.2.1

Rationale Sec. 3.2.2.1

H&S Sec. 7.1 p. 179

Read sequentially: prev next up top

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.8

Practically speaking, what is the difference between arrays and pointers?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Arrays automatically allocate space, but can't be relocated or resized. Pointers must be explicitly assigned to point to allocated space (perhaps using malloc), but can be reassigned (i.e. pointed at different objects) at will, and have many other uses besides serving as the base of blocks of memory.

Due to the so-called equivalence of arrays and pointers (see question 6.3), arrays and pointers often seem interchangeable, and in particular a pointer to a block of memory assigned by malloc is frequently treated (and can be referenced using []) exactly as if it were a true array. See questions 6.14 and 6.16. (Be careful with sizeof, though.)

See also questions 1.32 and 20.14.

Read sequentially: prev next up top

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.9

Someone explained to me that arrays were really just constant pointers.

This is a bit of an oversimplification. An array name is ``constant'' in that it cannot be assigned to, but an array is not a pointer, as the discussion and pictures in question 6.2 should make clear. See also questions 6.3 and 6.8.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.11

I came across some ``joke'' code containing the ``expression'' 5["abcdef"] . How can this be legal C?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Yes, Virginia, array subscripting is commutative in C. This curious fact follows from the pointer definition of array subscripting, namely that a[e] is identical to *((a)+(e)), for any two expressions a and e, as long as one of them is a pointer expression and one is integral. This unsuspected commutativity is often mentioned in C texts as if it were something to be proud of, but it finds no useful application outside of the Obfuscated C Contest (see question 20.36).

References: Rationale Sec. 3.3.2.1

H&S Sec. 5.4.1 p. 124, Sec. 7.4.1 pp. 186-7

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.12

Since array references decay into pointers, if arr is an array, what's the difference between arr and &arr?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The type.

In Standard C, &arr yields a pointer, of type pointer-to-array-of-T, to the entire array. (In pre-ANSI C, the & in &arr generally elicited a warning, and was generally ignored.) Under all C compilers, a simple reference (without an explicit &) to an array yields a pointer, of type pointer-to-T, to the array's first element. (See also questions 6.3, 6.13, and 6.18.)

References: ANSI Sec. 3.2.2.1, Sec. 3.3.3.2

ISO Sec. 6.2.2.1, Sec. 6.3.3.2

Rationale Sec. 3.3.3.2

H&S Sec. 7.5.6 p. 198

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.13

How do I declare a pointer to an array?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Usually, you don't want to. When people speak casually of a pointer to an array, they usually mean a pointer to its first element.

Instead of a pointer to an array, consider using a pointer to one of the array's elements. Arrays of type T decay into pointers to type T (see question 6.3), which is convenient; subscripting or incrementing the resultant pointer will access the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally useful only when operating on arrays of arrays, if at all. (See question 6.18.)

If you really need to declare a pointer to an entire array, use something like ``int (*ap)[N];'' where N is the size of the array. (See also question 1.21.) If the size of the array is unknown, N can in principle be omitted, but the resulting type, ``pointer to array of unknown size,'' is useless.

See also question 6.12.

References: ANSI Sec. 3.2.2.1

ISO Sec. 6.2.2.1

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.14

How can I set an array's size at run time?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

How can I avoid fixed-sized arrays?

The equivalence between arrays and pointers (see question 6.3) allows a pointer to malloc'ed memory to simulate an array quite effectively. After executing

#include <stdlib.h> int *dynarray = (int *)malloc(10 * sizeof(int));

(and if the call to malloc succeeds), you can reference dynarray[i] (for i from 0 to 9) just as if dynarray were a conventional, statically-allocated array (int a[10]). See also question 6.16.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.15

How can I declare local arrays of a size matching a passed-in array?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

You can't, in C. Array dimensions must be compile-time constants. (gcc provides parameterized arrays as an extension.) You'll have to use malloc, and remember to call free before the function returns. See also questions 6.14, 6.16, 6.19, 7.22, and maybe 7.32.

References: ANSI Sec. 3.4, Sec. 3.5.4.2

ISO Sec. 6.4, Sec. 6.5.4.2

Read sequentially: prev next up top

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.16

How can I dynamically allocate a multidimensional array?

It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated ``row.'' Here is a twodimensional example:

#include <stdlib.h> int **array1 = (int **)malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array1[i] = (int *)malloc(ncolumns * sizeof(int));

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

(In real code, of course, all of malloc's return values would be checked.)

You can keep the array's contents contiguous, while making later reallocation of individual rows difficult, with a bit of explicit pointer arithmetic:

int **array2 = (int **)malloc(nrows * sizeof(int *)); array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int)); for(i = 1; i < nrows; i++) array2[i] = array2[0] + i * ncolumns;

In either case, the elements of the dynamic array can be accessed with normal-looking array subscripts: arrayx[i][j] (for 0 <= i < NROWS and 0 <= j < NCOLUMNS).

If the double indirection implied by the above schemes is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array:

int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));

However, you must now perform subscript calculations manually, accessing the i,jth element with array3[i * ncolumns + j]. (A macro could hide the explicit calculation, but invoking it would require parentheses and commas which wouldn't look exactly like multidimensional array syntax, and the macro would need access to at least one of the dimensions, as well. See also question 6.19.)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Finally, you could use pointers to arrays:

int (*array4)[NCOLUMNS] = (int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));

but the syntax starts getting horrific and at most one dimension may be specified at run time.

With all of these techniques, you may of course need to remember to free the arrays (which may take several steps; see question 7.23) when they are no longer needed, and you cannot necessarily intermix dynamically-allocated arrays with conventional, staticallyallocated ones (see question 6.20, and also question 6.18).

All of these techniques can also be extended to three or more dimensions.

Read sequentially: prev next up top

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.17

Here's a neat trick: if I write

int realarray[10]; int *array = &realarray[-1];

I can treat array as if it were a 1-based array.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Although this technique is attractive (and was used in old editions of the book Numerical Recipes in C), it does not conform to the C standards. Pointer arithmetic is defined only as long as the pointer points within the same allocated block of memory, or to the imaginary ``terminating'' element one past it; otherwise, the behavior is undefined, even if the pointer is not dereferenced. The code above could fail if, while subtracting the offset, an illegal address were generated (perhaps because the address tried to ``wrap around'' past the beginning of some memory segment).

References: K&R2 Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6

ANSI Sec. 3.3.6

ISO Sec. 6.3.6

Rationale Sec. 3.2.2.3

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.18

My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The rule (see question 6.3) by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays can be confusing, and must be treated carefully; see also question 6.13. (The confusion is heightened by the existence of incorrect compilers, including some old versions of pcc and pcc-derived lints, which improperly accept assignments of multi-dimensional arrays to multi-level pointers.)

If you are passing a two-dimensional array to a function:

int array[NROWS][NCOLUMNS]; f(array);

the function's declaration must match:


f(int a[][NCOLUMNS]) { ... }

or
f(int (*ap)[NCOLUMNS]) /* ap is a pointer to an array */ { ... }

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

In the first declaration, the compiler performs the usual implicit parameter rewriting of ``array of array'' to ``pointer to array'' (see questions 6.3 and 6.4); in the second form the pointer declaration is explicit. Since the called function does not allocate space for the array, it does not need to know the overall size, so the number of rows, NROWS, can be omitted. The ``shape'' of the array is still important, so the column dimension NCOLUMNS (and, for three- or more dimensional arrays, the intervening ones) must be retained.

If a function is already declared as accepting a pointer to a pointer, it is probably meaningless to pass a two-dimensional array directly to it.

See also questions 6.12 and 6.15.

References: K&R1 Sec. 5.10 p. 110

K&R2 Sec. 5.9 p. 113

H&S Sec. 5.4.3 p. 126

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.19

How do I write functions which accept two-dimensional arrays when the ``width'' is not known at compile time?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

It's not easy. One way is to pass in a pointer to the [0][0] element, along with the two dimensions, and simulate array subscripting ``by hand:''

f2(aryp, nrows, ncolumns) int *aryp; int nrows, ncolumns; { ... array[i][j] is accessed as aryp[i * ncolumns + j] ... }

This function could be called with the array from question 6.18 as
f2(&array[0][0], NROWS, NCOLUMNS);

It must be noted, however, that a program which performs multidimensional array subscripting ``by hand'' in this way is not in strict conformance with the ANSI C Standard; according to an official interpretation, the behavior of accessing (&array[0][0])[x] is not defined for x >= NCOLUMNS.

gcc

allows local arrays to be declared having sizes which are specified by a function's arguments, but this is a nonstandard extension.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

When you want to be able to use a function on multidimensional arrays of various sizes, one solution is to simulate all the arrays dynamically, as in question 6.16.

See also questions 6.18, 6.20, and 6.15.

This page by Steve Summit // Copyright 1995 // mail feedback

Question 6.21

Why doesn't sizeof properly report the size of an array when the array is a parameter to a function?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The compiler pretends that the array parameter was declared as a pointer (see question 6.4), and sizeof reports the size of the pointer.

References: H&S Sec. 7.5.2 p. 195

Read sequentially: prev next up top

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

This page by Steve Summit // Copyright 1995 // mail feedback

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

PIC and Hi-Tech C FAQ


Last updated 1 Jan 2002.

This FAQ contains the top 68 questions and techniques asked by PIC micro students about HiTech C from University of Canterbury. This FAQ contains over 100k of pure text. Enjoy I sincerely hope this advice saves you a lot of time and effort. Fundamentals of PIC and Hi-Tech C Q. Q. Q. What are the most commonly used features of a PIC micro? So, how do I use the features listed in the previous question? Tell me how to drive the pins on a PIC micro

The experience for this FAQ taken from a degree in Electrical Engineering (Beng. Elec. Hons.), at University of Canterbury, th tutoring students for a 4 year Canterbury University Electrical Engineering design course, and 2 years commercial programming with PIC micros for Keyghost Ltd. and the KeyGhost project. The KeyGhost allows one to record keystrokes on a PC by plugging a tiny device into the keyboard cable.

Researching Data Q. Q. How do I find suppliers of Microchip parts? How to I do research on a new project?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Tips for using features of C on a PIC micro Q. Q. Q. Q. Q. Q. Q. Q. Q. Q. Q. How do I express numbers in decimal, hexadecimal or binary? Whats wrong with the following code ? Whats wrong with the following code ? What datatypes are available on a PIC? How do I switch bits on and off in a variable? How do I test bits in a variable? How do I divide or multiply by two efficiently? How do I reference one of the bytes in an integer? Doesnt x>>=8 have 8 shifts? Why dont you use pointers to look at individual bytes in an integer? Can I use inline code for functions? Q. Whats wrong with my port initialization code? "... I work for Flinders University and we hand out your Hi-Tech PICC FAQ to our students. Thanks for your work there." Craig Peacock http://www.beyondlogic.org/

Watching the values of variables Q. Q. Q. How do I watch variables in MPLab? How do I watch an array of variables in MPLab? I cannot view local variables in the watch window

Errors and what they mean Q. I get the following errors or line of errors when I compile

Weird quirks of the PIC micro Q. Q. Q. PORTA doesnt work when reading logic levels Port RA4 doesnt work My A/D doesnt work Q. Unexplained Operation and Stack Levels

Interesting quirks of Hi-Tech C Q. Whats wrong with the following program? It gives errors

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Serial Port with PIC Q. Q. Q. Im communicating to a PC with a serial port. It wont work. How do I fix it? My serial port sometimes dies completely, it wont receive anything more I want a routine to do a serial port in software Awesome resource, one of the best I've seen. Thanks for sharing! Alex Joseph Firmware Engineer Northstar Technologies 978-889-2110

Interrupts Q. Q. Q. Q. Q. How do I use interrupts? My interrupt routine is not working How do I tell what pin on RBIF the interrupt came from? How do I execute some code precisely every 800us at 4MHz? How do I speed up my interrupts? Q. How do I time exact intervals? Q. Whats wrong with the following interrupt code?

Simulator/Emulator Breakpoint Problems Q. I cant seem to get a breakpoint in the right spot

Emulator Problems Q. Q. My circuit works with the emulator, but not if I plug in a programmed chip My program works with the ICEPIC 2000 but not the ICD emulator

Watchdog Timer Q. Q. What is the watchdog timer and why do I want it? My programmed PIC, restarted itself every couple of seconds

Useful techniques for using C with PIC Q. Q. Q. Q. Q. Have you got any delay routines? How do I measure the time code takes? How do I make a variable oscillate, ie: go 1-0-1-0 How do I reset the micro? How do I tell what the compilers called a variable in the manual?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Q. Q. Q. Q. Q.

Whats the rule of thumb for timeouts? I need more space in the micro 8k is not enough for a 16F876 Can I use printf() when talking to a PC computer via the RS232 serial port Why cant I print long (32 bit) variables with printf()? How do I store large amounts of data?

Hardware for PIC Q. Q. Q. Q. Can I control 2 LEDs from one port? I want to protect my circuit from overcurrents and shorts How do I save power in my embedded micro system? My PIC sometimes resets by itself

Bootloader for PIC16F87x Q. How do I do a bootloader for the flash based 16F87x?

Simple Multitasking Kernel for PIC under Hi-Tech C Q. Example of simple multitasking system

Tips for using the PICSTART Plus Programmer Q. Q. Q. How do I embed the programming configuration words within my C program? The programmer doesnt seem to work it doesnt program It always loses settings for the programmer when I exit

Using Libraries with MPLab Q. Q. Q. What is a library, consisting of a ".lib" file, and how do I use it? How do I make a library file? I make a library file ending in ".lib" but I cant tell MPLab how to get to it Serial Numbers with Hi-Tech C Q. How do I add serial numbers to a program coded in Hi-Tech C?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Incremental Compiles under Hi-Tech C Q. How do I do incremental compiles under Hi-Tech C?

The PIC12Cx67x Q. How do I set the OSCCAL calibration bits?

Fundamentals of PIC with Hi-Tech C


Q. What are the most commonly used features of a PIC micro? A. In my experience, the following: Output ports for driving LEDs, etc Input ports for reading logic levels Timers that count in the background External interrupts that trigger the interrupt routine if a port changes Internal interrupts that trigger the interrupt routine if a timer overflows Serial port USART for communicating with a PC A/D ports for reading voltages Capture ports that can precisely capture the exact time of a port logic change. I2C, a standard by Philips that allows comms to multiple devices on a 2-wire bus SPI, transferring data using a CLK and DATA line Counters, can count external pulses in hardware and give the result a register SLEEP mode, to reduce power consumption Watchdog timer, to increase reliability by resetting micro if it crashes Q. So, how do I use the features of the PIC micro listed in the previous question? A. Well, this may sound obvious, but the best way is to follow through the Microchip microprocessor manual. Do it step by step. Dont succumb to the urge to do it now - complete the reading first, then do programming. This way, you avoid missing crucial pieces of information that you will need to get it working.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Rule of thumb: When using a new feature of the PIC micro for the first time, read every word in that section of the manual. To skim read it means you will miss out some crucial feature. For example, to use the A/D port, look up the manual, and follow through it. All the variables like ADCON1, etc have the same name in C. To get a list of all the equivalent names for the registers in C, go to c:\ht-pic\include subdirectory and look at the header files. This is very useful file to have for reference. Q. Tell me how to drive the pins on a PIC micro. A. Take the PIC16F876, a 28-pin micro. Then look at port A for example. This is a row of 6 pins, going down the side of the micro. Each pin can output 5V or 0V, or read whether the input is 5V or 0V. Here is sample C code to write a logic level to a port. A value of 1 will product 5V, a 0 will produce 0V. //(c)Shane Tolmie, http://www.workingtex.com/htpic/, distribute freely for non commercial use, you must include this comment. #include <pic.h> //designed for PIC16F876 main() { #define OUTPUT 0 #define INPUT 1 ADCON1=7; //switch all pins in port A to digital (otherwise it tries to do A/D) TRISA0=OUTPUT; //change port RA0 direction to output RA0=1; //produce 5V on RA0, pin 2 of micro RA0=0; //produce 0V on RA0, pin 2 of micro } Alternatively, you can read the value of the logic level on a port. If it is 0V, it will return a 0, it it is 5V, it will return a 1. Here is sample C code. //(c)Shane Tolmie, http://www.workingtex.com/htpic/, distribute freely for non commercial use, you must include this comment. #include <pic.h> //designed for PIC16F876 main() { unsigned char x; #define OUTPUT 0 #define INPUT 1

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

ADCON1=7; TRISA0=INPUT; x=RA0; }

//switch port A to digital (otherwise it tries to do A/D) //change the port direction to input //now x=0 if RA0=0 volts, and x=1 if RA0=5V.

Researching Data
Q. How do I find suppliers of Microchip parts? A. Go to the Microchip web site and look up the list of distributors in your country. This technique works for any company get their info on who distributes for them. Also, try http://www.findchips.com/ or http://www.freetradezone.com/. I have found this site to be helpful for comparisons between companies/products and within the microchip line itself. It has been very helpful to see right at the beginning that the chips are so easy to get, cheap, and varied. Q. How to I do research on a new project? A. Well, there are many places to find information on what you intend to do. 1. Read books and magazines. The advantage of these over the internet are that the signal-to-noise ratio is extremely high, and the articles are likely to be more correct. For books, search http://www.amazon.com/ for pic micro then get it out at your local library or buy it. Good magazines are Circuit Cellar, Electronics Australia, Popular Science and Popular Mechanics, among others. rd 2. Look up previous years projects for other students that have completed 3 pro design. By reading their report, you can gain sample code and ideas from their writeup. 3. Collect application notes. All the major manufacturers like Philips, Motorola, Atmel, Microchip, Intel, National Semiconductor, TI and Zilog have sample projects to illustrate the use of their devices. Look on their web sites under Application Notes, or do a search for 'application notes' 4. Find the official standards. It may be nice to download information off the web compiled by some well meaning person, but in my experience dont be satisfied until you have the official documentation. Information compiled by a private individual may be only mostly correct. 5. Put out a request for information on the web. For the best results, go to http://www.copernic.com/ and download their search program. It is better than web based searches and extremely fast. I use it exclusively now, as it gets the best results, culled and sorted from the best search engines. You can use newsgroups on the internet such as comp.arch.embedded. The Hi-Tech site, http://www.htsoft.com/ has an inhouse newsgroup devoted to PIC questions on their compiler.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

6.

Subscribe to piclist, http://www.piclist.com/ to ask any question of thousands of PIC enthusiasts. Search the piclist archive, from http://www.piclist.com/ to look at previous postings. Look at the PIC webring http://nav.webring.com/cgi-bin/navcgi?ring=picmicro;list which is a collection of sites related to the PIC micro. Search for pic micro on http://www.google.com/, one of the best web-based search engines out there. Ask the experts. You can email Microchip or Hi-Tech with any questions on their products.

Tips for using features of C on a PIC micro


Q. How do I express numbers in decimal, hexadecimal or binary? A. Use the following code: unsigned char x; x=255; x=0xFF; x=0b11111111; //8 bits on PIC //give hex number, x=255 //give binary number, x=255

Q. Whats wrong with the following code? unsigned char x; x=0b1111111; //set x to 0xFF or 255 A. Can you figure it out without looking at the answer? Its a simple error, but its easy to glance over and miss. Throughout history, it has caused countless hours of wasted time. 0b1111111=127, not 255, as the last 1 is missing. Binary values always come in groups of 8 bits, and one should always mentally check that 8 bits have been entered. Q. Whats wrong with the following code? unsigned char i; for (i=7;i>=0;i--) { };

//BAD BUG will loop forever

A. Ah. A very insidious bug. When it gets to zero, it decrements it and then checks to see whether its still higher than zero. But, of course, since its unsigned it has already rolled over to 255. Thus it will loop until the next blue moon. Change variable i to signed, as below:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

signed char i; for (i=7;i>=0;i--) { }; //works correctly Note that when counting up from 0, chars can be both signed and unsigned as there is no rollover problem. Q. What datatypes are available on a PIC? A. The following: unsigned char a; signed char b; unsigned int c; signed int d; long e; float f;

//8 bits, 0 to 255 //8 bits, -128 to 127 //16 bits, 0 to 65535 //16 bits, -32768 to 32767 //32 bits, -2147483648 to 2147483647 //24 or 32 bits, depending on options under edit project

Q. How do I switch bits on and off in a variable? A. Use the following code for turning single bits on or off in a variable. Remember that the bits in an 8-bit variable are always numbered from right to left, 0 to 7. For example, bit 0 of 0b00000001 is 1. Bit 1 is 0. /*for turning single bits on/off in a variable. Use ~0 instead of 0xFFFF, etc, because this ensures machine independence, if int changes from 16-bit to 32-bit. Remember that the bits in an 8-bit variable are always numbered from right to left, 0 to 7. For example, bit 0 of 0b00000001 is 1. Bit 1 is 0, through to the most significant bit 7 on the left. Example C: unsigned char x=0b0001; bit_set(x,3); //now x=0b1001; bit_clr(x,0); //now x=0b1000;*/ #define bit_set(var,bitno) ((var) |= 1 << (bitno)) #define bit_clr(var,bitno) ((var) &= ~(1 << (bitno))) Use the following code for turning multiple bits on or off in a variable, according to mask. /*for turning multiple bits on/off according to mask. Use ~0 instead of 0xFFFF, etc, because this ensures machine independence if int changes from 16-bit to 32-bit.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Example C: unsigned char x=0b1010; bits_on(x,0b0001); //now x=0b1011 bits_off(x,0b0011); //now x=0b1000 */ #define bits_on(var,mask) var |= mask #define bits_off(var,mask) var &= ~0 ^ mask Q. How do I test bits in a variable? A. Use the following code: /*for testing single bits in a variable. Remember that the bits in an 8-bit variable are always numbered from right to left, 0 to 7. For example, bit 0 of 0b00000001 is 1. Bit 1 is 0, through to the most significant bit 7 on the left. Example C: x=0b1000; //decimal 8 or hexadecimal 0x8 if (testbit(x,3)) a(); else b(); //function a() gets executed if (testbit(x,0)) a(); else b(); //function b() gets executed if (!testbit(x,0)) b(); //function b() gets executed */ #define testbit_on(data,bitno) ((data>>bitno)&0x01) Q. How do I divide or multiply by two efficiently? A. To multiply by two, use x = x << 1 or x<<=1. The second version is shorthand. If x=2, or 0b10 in binary, shifting left gives 0b100 or 4. To multiply by four, use x<<=2. By eight, x<<=3. To divide by two, use x>>=1. To divide by four, use x>>=2. Having said this, most compilers would optimise a x=x/2 into a shift anyway. Q. If an integer is 16 bits on a PIC, and a byte is 8 bits, how do I reference one of the bytes in an integer? A. Use the following code: unsigned int x;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

unsigned char y; #define hibyte(x) (unsigned char)(x>>8) #define lobyte(x (unsigned char)(x & 0xFF) x=0x1234; y=hibyte(x); //now y=0x12 y=lobyte(x); //now y=0x34 /*note: the above method is as efficient as pointers, as with Hi-Tech C the optimiser picks out the right byte of course, (x>>7) would result in 7 shifts. Local and Global optimisations must be on*/ Note the use of typecasting when converting any variable to another type, one should typecast it. Read a book on C to explain this further. Note, unions are not necessary and are not recommended because passing variables to functions is made more difficult. The above method is good for looking at any variable in any bank of memory. Unfortunately, it cannot be used to alter a byte in an int. For this, pointers are needed. A different #define is needed to alter variables in each bank. #define #define #define #define lobyte_atbank0(x) hibyte_atbank0(x) lobyte_atbank1(x) hibyte_atbank1(x) (unsigned (unsigned (unsigned (unsigned char)(*(((unsigned char *)&x)+0)) char)(*(((unsigned char *)&x)+1)) char)(*(((bank1 unsigned char *)&x)+0)) char)(*(((bank1 unsigned char *)&x)+1))

See special header file for a complete list. Download. Q. Is the following code inefficient? Doesnt x>>=8 have 8 shifts? unsigned int x; unsigned char y; x=0xFF00; y=(unsigned char)(x>>8);

//now y=0xFF

A. No. Its very efficient the Hi-Tech C compiler goes through and just refers directly to the top byte out of the int. Local and global optimisations must be on in the project. Of course, y=x>>7 would have 7 shifts and take a long time on a PIC. Q. Instead of using (unsigned char)(x>>8) as per the previous question, why dont you use pointers?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A. It is possible, but because there is 4 banks of memory it needs a different #define for variables in each bank. Its simpler and effectively the same to use (unsigned char)(x>>8), unless youre altering the variable. Q. Whats the difference between the following two lines of code: x++; if (x>=4) x=0; x++; if (x==4) x=0; A. Its a very minor point, but the first statement is more robust. If a rogue pointer or a chip brownout corrupts x, it will count all the way up to the max before wrapping around. Of course, one may want such errors to show up, so the second one may be more preferable. Q. Can I use inline code for functions? A. On some compilers, adding the keyword inline before a procedure means that each time the procedure is called, the code inside it is inserted rather than called. This reduces the overhead of jumping to the function, but makes the program larger. There is no inline keyword for the latest version of Hi-Tech C, v7.85. However, one can almost have inline code by using #defines. If one puts a \ character after each line, it treats it like a single large line. The only disadvantage is that there is no way to return a variable. For example, see the following code. unsigned char x,y #define domaths_inline(z) \ x+=z; \ y++; void domaths_procedure(unsigned char z) { x+=z; y++; } main() { domaths_inline(4); //puts instructions x+=4;y++ directly into program domaths_procedure(4); //calls procedure which executes instructions x+=4;y++ } Q. Whats wrong with the port initialization code below?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

//these #define #define #define #define

4 lines are correct INPUT 1 OUTPUT 0 CLOCK RB1 CLOCK_DIRECTION TRISB0

//method 1 - set direction, then port (CORRECT) // CORRECT CLOCK_DIRECTION=OUTPUT; DelayUs(10); //delay 10 microseconds CLOCK=1; //method 2 - set port then direction (WRONG) // WRONG - MAY LEAVE PORT VALUE AS 0 CLOCK=1; DelayUs(10); //delay 10 microseconds CLOCK_DIRECTION=OUTPUT; Of the two methods above, method is 1 is correct, method 2 is wrong. If method 2 is used, clock will be set to 1, but since clock is an input, it will change back to a 0 again if the input is a zero. When the port is set to an output, it may be a zero or a one. Thus, if method 2 is used to set up ports, the port could end up initialized to a zero, instead of a 1. With the correct method 1, clock is initially an input. Thus, the value of clock reflects the read value of that port. Thus, setting any port from an input to an output wont change the value of the port. Once the value of the port is set, it can be changed to another value. Rule of thumb: when changing ports from input -> output, always set direction first, then change value.

Watching the values of variables


Q. How do I watch variables in MPLab?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A. Bring up the watch window dialog by clicking on the pair of glasses icon on the right of the menu bar. 1. 2. 3. Char variables are 8 bits can be displayed in a variety of formats. Integer variables are 16 bits and the byte order is low:hi in every case, as shown below. Long variables are 32 bits and the byte order is low:hi in every case, as shown below.

Of course, to display variables inside functions, the switch -fakelocal must be added to the linker options. For this switch to work, check that you have the latest version of Hi-Tech C, v7.86pl3 or above. This is explained in the tutorial on how to set up a project.

Q. How do I add another variable to a watch window? A. Left click to the left of the Watch_1 title on the title bar, as below.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Q. How do I watch an array of variables in MPLab? A. There is no built in way and in MPLab to view arrays of variables. There is a way to get around it, illustrated by the diagram below. To look at the array named array, select main.array from the add watch symbol box. This is address 0x21, and shows array[0]. To look at array[1] enter 0x22 as the symbol. Alternatively, to view an array of integers, increment the address by two each time.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Q. I cannot view local variables, only global variables appear in the watch window. A. To display variables inside functions, the switch -fakelocal must be added to the linker options. This is explained in the tutorial on how to set up a project. For this switch to work, check that you have the latest version of Hi-Tech C, v7.85 or above.

Errors and what they mean


Q. I get the following errors or line of errors when I compile: ::Can't find 0x64 words for psect rbss_0 in segment BANK0 (error) A. All this gibberish means is that theres not enough ram to fit the variables in. In the 16F876, there are 4 banks of 96 bytes. Move some variables to another bank, by the following method:

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

unsigned char array_char[79]; bank1 unsigned int array_int[40]; bank2 unsigned long array_long[24]; bank3 float array_float[30]; After this, use the variables as per normal.

//goes //goes //goes //goes

in in in in

bank0, bank1, bank2, bank3,

96 96 96 96

bytes bytes bytes bytes

excluding excluding of 32-bit of 24-bit

overhead overhead longs floats

However, there are some issues with passing pointers. For example, a function that accepts a pointer can only accept it from the same bank. This is illustrated by the code below. /* the following C line wouldnt work have to specify bank where pointer comes from, otherwise produces error :Fixup overflow in expression*/ //strcpy(unsigned char *to,unsigned char *from) //works fine strcpy(bank2 unsigned char *to,bank1 unsigned char *from) { while(*to++ = *from++); //copies strings } bank1 unsigned char x[3]; bank2 unsigned char y[3]; main() { x[0]=O;x[1]=K;x[2]=0; strcpy (&y[0],&x[0]); }

//x contains string Ok //now array y contains string Ok

The following error is produced by passing pointers in different banks, so to fix it refer to the code above. project.obj:33:Fixup overflow in expression (loc 0xFD2 (0xFCC+6), size 1, value 0xA1) (error)

Weird quirks of the PIC micro


Q. PORTA doesnt work when reading logic levels.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A. Set it to digital mode, by setting ADCON1=7. If its in analogue mode, it will try to do a/d operations on the port. Q. Port RA4 doesnt work. A. Port RA4 requires a 10k pullup. This is because it can be the input for an external timer. Q. My A/D doesnt work. A. Check out the sample files in the c:\ht-pic\samples\ directory for an example. Here is example code for the PIC16F876/77. Download. Q. Unexplained Operation and Stack Levels A. The PIC16F87x has 8 stack levels. This means that function calling in C can be nested up to 8 times. If function calling is nested more than this, unexplained operation will occur, because the oldest return addresses are overwritten. Realistically, function calling can only be nested 7 times, because the interrupts use 1, if not more, stack levels. If you interrupt service routine (ISR) calls a 1 function then 2 stack levels are used just for the interrupt. Note that the ISR should never, under any circumstances, call any functions if you use Hi-Tech C. This is because the ISR has to save the function calling area, which takes lots of precious cycles. The unexplained operation is characterised by the program jumping to functions that it shouldnt be in. If you are unsure, always check to see how many stack levels your program uses. Unfortunately, the hardware stack on a PIC micro is not readable or accessible by the program. The best way to check the amount of stack levels used, in Hi-Tech C, is to look at the .map file. Turn on .map files in the linking options. In MPLab, select Project..Edit Project..Node Properties..Map File On.."main.map". Manually check how many levels the function calling is nested. Allow as many stack levels for the interrupts as needed. Another way is to manually keep a track of the stack levels with a counter. Every time a function is called, increment the counter. Every time a function is returned from, decrement the counter. Keep a track of the maximum number this counter gets to, ie: stack_level++;if (stack_level>stack_level_max) stack_level_max=stack_level; However, this method is not recommended. If your program is big enough to warrant checking for stack levels, it will be a royal pain to add all the calls. A #define makes it easier, also used to switch on/off the debug code, but even still, examining the .map file is much more reliable, quicker, and doesnt make the program larger.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Interesting quirks of Hi-Tech C


Generally, Hi-Tech C is a very stable, bug free compiler. In two years of using it, I have never encountered any trouble with it. Currently I have an 8k, 5000 line C program that works beautifully. Make sure that you have the latest version, v7.86pl2, as some earlier versions have bugs. For example, v7.84 without the patch level 1 would sometimes branch the wrong way in an if..else statement if the variables were in different banks. Q. Whats wrong with the following program? It gives errors. #define DOMATHS \ x++; \ y++ #include <pic.h> unsigned char x,y; main() { DOMATHS; } <- invisible space or tabs after \ gives error

A. An insidious problem. Check that theres no invisible spaces after any of the \ characters. Do this by moving the cursor to every line with a \, and pressing the <end> key. Symptoms? It will generate multiple errors, with the one below as the last one. c:\pic\main.c: 12: illegal character (0134) (error)

Serial Port with PIC


Q. Im using a 16F876 PIC micro to communicate to a PC with a serial port. It wont work. How do I fix it? A. Here is PIC Hi-Tech C code, schematic picture and protel 99 files, plus VB 6 example code. Download.

1. Do you have Hyperterminal set to the correct COM port, N,8,1 with no flow control? 2. Get an oscilloscope, and put it in pin 3 of the serial port. Type some characters, and you should see it coming up on the oscilloscope. 3. Connect pins 2 and 3 on the serial cable. This makes a loopback. Everything you type in Hyperterm will be displayed instead of lost.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

4. The PIC sends out 5V logic levels. The serial line operates with 13V/+13V logic levels. Some sort of interface is needed, usually using a 5. 6. 7. 8.
MAX232, MAX3222 or SIPEX232 chip. Look up the datasheet and check that you have got it right. Check the capacitor values. The capacitors need to be a minimum size, anything above this will do. 33uF electrolytic caps are fine, if a bit of an overkill. Make sure that the order of the lines into the MAX232 chip is correct, as above. Check it from the micro side of things. Run the program, downloaded above, and verify that 5V logic levels are coming out of the transmit (TX) pin. Check that the crystal speed matches the value used to calculate SPBRG and BRGH. If you are using the ICEPIC 2000, check that the crystal speed, set in the menu options, matches the ones used to calculate SPBRG and BRGH. Send out 0xAA, which is 10101010 in binary. Using the oscilloscope, measure the time between the pulses and verify that they match the baud rate. If all else fails, change computer and try it on another.

Q. My serial port sometimes dies completely, it wont receive anything more. A. This means you are ignoring framing and overrun error bits. If too many characters are received before they are recorded in software, the overrun bit, OERR, gets set. This shuts off all further transmissions. It a wrong stop bit is received, the framing error bit, FERR, gets set. This shuts off all further transmissions. See the project for serial comms in the sample projects section. Q. I want a routine to do a serial port in software, because Im using a low-end PIC. Go to directory c:\ht-pic\samples and look at files serial.c and iserial.c. The second file receives characters into a buffer in the background, using interrupts. Its almost like the hardware serial port on a high-end PIC.

Interrupts
Q. How do I use interrupts? A. Interrupts are very useful. When a certain event happens such as the logic level on a port changing, a timer overflowing or a serial character arriving a flag is set. For example, if the logic level on port RB0 changes, instantly the flag INTF will get set. If the particular interrupt is enabled, the current state of the processor is saved, and execution branches to the interrupt routine.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

For example, if INTE is enabled, then it will jump to the interrupt routine as soon as INTF is set. When it is finished, the state of the processor is retrieved and execution continues where it left off. Here is sample code to read the data line if the clock line goes low #include <pic.h> main() { //set up capture port interrupt CCP1CON=0B00000100; //every falling edge of clock interrupts it CCP1IE=1; //enable capture port interrupt on data line PEIE=1; GIE=1; //global interrupt enable while(1); //whiz around doing nothing until interrupted, it jumps to isr } /*note the keyword interrupt. Hi-Tech C handles the code to save and restore the state of the micro, and the calculating the address to hook into the interrupt*/ interrupt isr() { //when clock line goes low, falling edge, it reads data line if (CCP1IF) //clock line falling edge on CCP1IF, RC2, pin 13 on micro { CCP1IF=0; //read data line in here } } Q. My interrupt routine is not working. A. Try the following tips: 1. If you put a breakpoint in the interrupt routine, and it doesnt get there, check that every variable in the interrupt chain is enabled. The diagram below has been reproduced from the PIC16F876 manual, from the section on interrupts. For example, to enable the interrupt on the 16bit timer 1 overflow, TMR1IE, PEIE and GIE must all be enabled for the interrupt to interrupt to CPU. If PEIE or GIE is disabled, it will never jump to the interrupt routine.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

2. You must clear the interrupt flag, and in some cases read the port involved with the interrupt before exiting the interrupt routine. Otherwise, it will keep going back into the interrupt routine continuously for ever. 3. Important: the rule of thumb involving volatile variables:

Every variable that is referred to in main() and interrupt must be declared volatile If a variable is not declared volatile, problems will arise if it is changed. This is because the optimiser makes the program store a temporary copy of the variable in a register. If the interrupt comes along and changes it, even though it is changed in ram, it is not changed in the register. Making a variable volatile forces the program to load a fresh copy of the variable every time it wants to check it. It also slows the program down slightly. Here is some sample code to illustrate when to make a variable volatile: //(c)Shane Tolmie, http://www.workingtex.com/htpic/, distribute freely for non commercial use, you must include this comment. //WRONG METHOD x IS REFERENCED IN BOTH MAIN() AND INTERRUPT //unsigned char x;

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

//correct method volatile unsigned char x; #define FALSE 0 #define TRUE 1 main() { INTE=1; GIE=1; x=FALSE; while(x==FALSE) { //idling loop waiting for interrupt to change x //if x is not declared volatile, it will check its value from a temporary //register. When the interrupt changes x in ram, it will never know. } //wait for interrupt to change x to true, reaching this portion of code } interrupt isr() { //interrupt on port RB0 change if (RBIF) { RBIF=0; x=TRUE; } } Q. Pins RB4 to RB7 all generate a common interrupt on change, RBIF. How do I tell what pin the interrupt came from? A. Keep a record of the previous state of the port, and use XOR to work out what pin changed, thus: //(c)Shane Tolmie, http://www.workingtex.com/htpic/, distribute freely for non commercial use, you must include this comment. #include <pic.h> main() {

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

//wait doing nothing } unsigned char prev_portb=0; interrupt isr() { //work out which pin portb changed to produce this interrupt if (RBIF) { RBIF=0; if ((prev_portb ^ PORTB) == 0B00010000) { //pin RB4 changed if ((PORTB & 0B00010000) == 0) { //now its 0, so its a falling edge //execute code here (only on falling edge) } } if ((prev_portb ^ PORTB) == 0B00100000) { //pin RB5 changed //execute code here (on pin change) } prev_portb=PORTB; } } Q. How do I execute some code precisely every 800us at 4MHz? A. Use the built in timer. Set it up so when it rolls over it triggers an interrupt. When the interrupt is triggered, it sets flag T0IF high and executes some code. For this example, we will use the 8-bit timer 0, available on PIC micros. If the micro is running at 4Mhz, it is executing instructions at clk/4 speed, or 1MIPS. This is 1 instruction every 1us. For 800us, we need 800 timer ticks before it rolls over.

RBIE=1; GIE=1; while(1);

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

The timer rolls over at 0xFF, or 255. 255 is smaller than 800, so use 4 lots of 200 ticks using a 1:4 prescaler. If we want 200 ticks, and the timer counts up and rolls over at 255, we need to set the timer to 55 each time, so it will count up to 255. Note that the prescaler is not rewritten each time this needs to be only set once initially. The manual seems to indicate that whenever tmr0 is rewritten, it rewrites the prescaler. However, it means that it zeros the internal counter for the prescaler, not the actual prescaler itself. This timing method is used in the simple multitasking technique for a PIC. In the meantime, here are some code examples. Method 1: execute code every 800us by using polling to check the bit in main() //(c)Shane Tolmie, http://www.workingtex.com/htpic/, distribute freely for non commercial use, you must include this comment. #include <pic.h> #define POLLING_PERIOD 200 //with 4Mhz processor, 200us #define TMR0_PRESCALER 1 //gives 1:4 prescaler //the -3 factor is to make up for overhead //the 0xff- factor is because the timer counts *up* to 0xff //do not change this #define TMR0_SETTING (0xff - (POLLING_PERIOD-3)) main() { OPTION&=0B11000000; //turn off bottom 6 bits to configure tmr0 OPTION|=TMR0_PRESCALER; //set prescaler to 1:4 while(1) { TMR0=TMR0_SETTING; T0IF=0; while(T0IF==0); //wait 800us for flag to go high //OK, tmr0 has overflowed, flag T0IF has gone high //this code right here is executed every 800us } } Method 2: generate an interrupt to execute code every 800us in background

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

//(c)Shane Tolmie, http://www.workingtex.com/htpic/, distribute freely for non commercial use, you must include this comment. #include <pic.h> #define POLLING_PERIOD 200 //with 4Mhz processor, 200us #define TMR0_PRESCALER 1 //gives 1:4, 800us //the -5 factor is to make up for overhead //the 0xff- factor is because the timer counts up to 0xff #define TMR0_SETTING (0xff - (POLLING_PERIOD-5)) main() { OPTION&=0B11000000; //turn off bottom 6 bits to configure tmr0 OPTION|=TMR0_PRESCALER; //set prescaler to 1:4 //work out which interrupt enable bits to set by referring to diagram T0IE=1; GIE=1; while(1) {

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

//idle, using interrupt to execute code } } void interrupt isr(void) { if (T0IF) { TMR0=TMR0_SETTING; T0IF=0; //code right here is executed every 800us } } Q. How do I speed up my interrupts? A. Here is a few tips: Execute the least amount of code possible in the interrupt, do all background processing in the main(). Trigger the tasks in main() by setting a flag in the interrupt which is polled in main(). See the debt counter project for an example of this. Do not use any functions in your interrupt. This means the compiler has to save the state of absolutely everything, so it slows it down. This is a problem of most compilers. Make everything inline or the equivalent by copying it straight in from the function. If you absolutely must have a function, to be on the safe side, use in-line assembly to call it. Double check how many cycles it takes to get into the interrupt. Here is an example for the PIC16F87x under Hi-Tech C. To check if your interrupt is saving too much state, in MPLab, in the ROM memory window, put a breakpoint at 0x0004, the entry point of the interupt service routine (ISR). Run the program until it interrupts. Then, single step until the program gets to the first C line in the ISR. This is how many cycles it takes to get into the interrupt. Q. Whats wrong with the following interrupt code? //incorrect code (if SSPIE or ADIE is being disabled/enabled in main) interrupt void isr (void) { if (SSPIF) { SSP_INT_SERV(); }

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

if (ADIF) { ADC_INT_SERV(); } //...add other ints here } Symptoms: The program hangs after some minutes. Use: if (ADIE && ADIF)... and etc. intead of if (ADIF). Consider what will heppen if you will disable AD interrupt for some reason (ADIE=0), and the SPI interrupt will occur. both handlers will be executed, not only the SPI handler as expected , because ADIF is set independetly of ADIE value. //correct code (if SSPIE or ADIE is being disabled/enabled in main) interrupt void isr (void) { if (SSPIF && SSPIE) { SSP_INT_SERV(); } if (ADIF && ADIE) { ADC_INT_SERV(); } //...add other ints here } Q. How do I time exact intervals? My favorite way to handle this 'non-commensurate' intervals problem is to steal a concept from the Bresenham line drawing algorithm. Using the current case: 4.00 MHz crystal 1Mhz instruction rate 256 cycles and prescaler of 64 each overflow of the timer represents 256*64 == 16384 microseconds

You start with a counter set to 1,000,000 (1 second in microseconds)

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

On each timer interrupt you subtract 16384 from the counter. If the counter goes negative you update the time by one second and then add 1,000,000 back in to the counter. This technique will work for any interval. It can be made perfect for intervals that have a rational relationship to the instruction cycle time, and can be abitrary close to perfect even for irrational ratios, for example a SQRT(2) Mhz crystal.

Simulator/Emulator Breakpoint Problems


Q. I cant seem to get a breakpoint in the right spot. It either wont put one on the line that I want it, or I cant stop on the right line. A. Theres a trick to setting breakpoints. See the closing bracket } in the code? It hasnt got 4 dots to the left of it. This means that you cannot right click on that line, and put a breakpoint there. As to making it stop on the right line, sometimes you have to add extra lines of code so it can stop exactly where you want it. Use the #define to set b (for breakpoint) to inline assembly language, asm(nop). Nop stands for No Operation it doesnt do anything.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Emulator Problems
Q. My circuit works with the emulator, but not if I plug in a programmed chip. A. Check the following: 1. The program may be wrong. Usually, the simulator and emulator environment has all variables are set to 0 initially. If a program doesnt initialise its variables, it will work in the simulator and emulator, but not on a standalone chip. Rule of thumb: Initialise every variable to a known value before using it 2. Is the chip programmed at all? 3. Is the chip programmed properly? XT for <8Mhz, HS for >8Mhz, etc. 4. Does the chip have power? Check 5V on the correct pins. 5. Is the reset pin pulled high with a 10k resistor? Check that pin 1 on micro is at 5V. 6. Is the crystal oscillating? Get an oscilloscope and touch it to the oscillator pins on the micro. They should both be buzzing. If ts not oscillating, it means either the chip is not programmed at all, or not programmed properly, the crystal is bad, the capacitors are the wrong value, or your circuit is broken or wrong somehow. Check manual. 15pF to 33pF is about right, depending on frequency. You can check the value of the capacitors down in the electronics lab with their component tester. 7. I all else fails, program up a chip with the following program, then check to see if the ports B is oscillating: #include <pic.h>

main() { TRISB=0x0; //output while(1) { PORTB=0;PORTB=0xFF; } } Q. My program works with the ICEPIC 2000 but not the ICD emulator.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A. Add the switch -ICD under the linker options, menu project then edit project then node properties. This reserves the last 256 bytes of memory, and 13 miscellaneous ram bytes that the ICD uses. Check the compiler is v7.85 or above. Then, match the ICD options to the box below.

These settings are the default for almost every situation, with the exception of the oscillator.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

1. 2. 3.

When using an external crystal with speeds of higher than 8Mhz use the settings as shown above. Crystal speeds of lower than 8MHz use XT for the oscillator setting instead HS. When using a RC oscillator for the clock, made up of a resistor and a capacitor, use RC for the oscillator setting instead of HS.

Watchdog Timer
Q. What is the watchdog timer and why do I want it? A. The watchdog is a good way to ensure that the microprocessor does not freeze forever from a crash, due to a bad power supply or a rogue program. When the chip is programmed, the watchdog timer bit is enabled. It cannot be turned off in software, in case a rogue program overwrites it. If the timer is not reset regularly with a CLRWDT() instruction, it will reset the micro. This will happen within 18ms to 2 seconds, depending on the prescaler selected.

Q. After I programmed my PIC, it kept restarting itself every couple of seconds. A. Have you got the watchdog timer bit set? The watchdog is a good way to ensure that the microprocessor does not freeze forever from a crash. When the chip is programmed, the watchdog timer bit is enabled. It cannot be turned off in software, in case a rogue program overwrites it. If the timer is not reset regularly with a CLRWDT() instruction, it will reset the micro. This will happen within 18ms to 2 seconds, depending on the prescaler selected, and on the temperature. It is interesting to note that it is possible to make a PIC into an accurate temperature sensor using the time of the watchdog timeout to sense the temperature. The advantage of using a watchdog timer is that the micro is protected from crashing forever due to a bad power supply or a rogue program.

Useful techniques for using C with PIC


Q. Have you got any delay routines? A. Its important to have accurate delay routines. Delay routines written in C arent accurate depending on optimisations, they can vary. Thats why some of the routines have inline assembly. Delay routines are available for download.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Q. How do I measure the time code takes? A. If youre using the simulator or the ICEPIC 2000, bring up the stopwatch under menu windows. Put breakpoints before and after the section of code, and measure the time.

The MPLAB-ICD doesnt have a stopwatch. Add a piece of code to read out the value of timer 1 at the start of the code, then check it again at the finish. The timer increments at the same frequency as instructions executed. Do some maths and you have the time in clock cycles that the code takes. Q. How do I make a variable oscillate, ie: go 1-0-1-0 A. Do the following code: unsigned char x; x=1-x;

//every time this statement is executed, x goes 1-0-1-0-1-0 etc

Q. How do I reset the micro? A. One way is to reset all variables to their defaults, as listed in the PIC manual. Then, use assembly language to jump to location 0x0000 in the micro.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#asm ljmp 0x0000 #endasm This is quite safe to use, even when called within interrupts or procedures. The PIC 16x series micros have 8 stack levels. Each time a procedure is called, one stack level is used up for the return address. It is a circular buffer, so even if the micro is 7 procedure levels deep and in an interrupt when a reset is called, this is the new start of the stack buffer, and the micro will continue as per normal. Another way is to set watchdog the timer when the chip is programmed, and use CLRWDT() instructions all through the code. When you want the micro to reset, stop clearing the watchdog bit and the micro will reset after around 18ms to 2 seconds depending on the prescaler. Q. Theres a variable in the PIC manual that the compiler doesnt recognise, even though I used the same name. How do I tell what the compilers called it? A. Go to directory c:\ht-pic\include\ and look at the header files. These give the names that the compiler gives to the internal variables. This is extremely useful for finding out exactly what variables are available in C. Heres some example code from the header file, pic1687x.h for the PIC16F87x micro: /* * Header file for the Microchip * PIC 16F873 chip * PIC 16F874 chip * PIC 16F876 chip * PIC 16F877 chip * Midrange Microcontroller */ //[added for FAQ] we can see that the compiler has called PORTA by the same name as the manual static volatile unsigned char PORTA @ 0x05; //[added for FAQ] ... the listing continues on ... /* PORTA bits */ static volatile bit RA5 @ (unsigned)&PORTA*8+5; static volatile bit RA4 @ (unsigned)&PORTA*8+4; //[added for FAQ] we now know that each bit in PORTA is called, for example, RA5, as per manual //[added for FAQ] ... the listing continues on ... Q. Whats the rule of thumb for timeouts?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A. Rule of thumb: every time a program waits for an operation that could fail, have a timeout to exit it after too much time. For example, reading in a byte with SPI. There is the clock and data line, and a byte with 8 bits is read into the micro. If the sender of the byte stops halfway through, there is four garbage bits remaining. Later on, after 5 minutes, the sender sends a new byte. Everything is now out of sync, with the first half going into one byte, and the last half going into the next. Use the following code to implement timeouts. //(c)Shane Tolmie, http://www.workingtex.com/htpic/, distribute freely for non commercial use, you must include this comment. // example of how to use timeouts: unsigned int timeout_int; //for max 491512us timeout @ 8Mhz //for max 245756us timeout @ 16Mhz timeout_int=timeout_int_us(500); while(timeout_int-- >= 1) { if (x==y) break; //typical overhead for checking ring buffer } if (timeout_int<=2) { //theres been too much time elapsed } //for max timeout of 1147us @ 8Mhz //for max timeout of 573us @ 16Mhz timeout_char=timeout_char_us(500); while(timeout_char-- >= 1) { if (x==y) break; //typical overhead for checking ring buffer } if (timeout_int<=2) { //theres been too much time elapsed } /* Time taken: optimisations on: 9cyc/number loop, 4.5us @ 8Mhz with extra check ie: && (RB7==1), +3cyc/number loop, +1.5us @ 8Mhz Formula: rough timeout value = (<us desired>/<cycles per loop>) * (PIC_CLK/4.0) */ #define LOOP_CYCLES_CHAR 9 //how many cycles per loop, optimisations on #define timeout_char_us(x) (unsigned char)((x/LOOP_CYCLES_CHAR)*(PIC_CLK/4.0)) #define LOOP_CYCLES_INT 16 //how many cycles per loop, optimisations on #define timeout_int_us(x) (unsigned int)((x/LOOP_CYCLES_INT)*(PIC_CLK/4.0))

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Q. I need more space in the micro 8k is not enough for a 16F876. A. Youve done well. One thing to check is that you havnt got any orphaned functions which are never called. Hi-Tech C includes the code, even though it is redundant. To automatically check for this, set the warning level to 9 (negative nine) under menu Project then Edit Project then node properties. This introduces all sorts of warnings. Most of them can be ignored, except the one: ::function _myfunction is never called (warning) This means that the code for the function myfunction is included somewhere in your code, but it is never called. If youre not going to use it, comment it out. You must have your project set up to 'compile at once' rather than 'linked' for the compiler to give this information. See tutorial. Q. Can I use printf() when communicating with a PC computer via the RS232 serial port? A. You can use printf() to write to the USART on a PIC micro if you define your own putch() routine and #include the correct header file. It uses an extra 650 words of program memory. See the sample code here. Q. Why cant I print long (32 bit) variables with printf()? A. Add the switch -lf to the additional command line options, under menu Project then Edit Project then Node Properties. This uses up a additional 1600 words of rom space, but it allows printf to print longs. Q. How do I store large amounts of data? A. Use EEPROM or the Dataflash available from Microchip or Atmel. Capacities range from 1Kbyte to 4Mbyte non-volatile chips.

Hardware for PIC


Q. Can I control 2 LEDs from one port?

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A. Yes. The only catch is that one has to be on at any time. Connect the 2 LEDs in series, between the 5V and GND rails. Attach the port to the middle between the LEDs. Connect a current limiting resistor in series between the VCC rail and the top LED, and between the GND rail and the bottom LED. Different color LEDs require different voltages acorss their terminals, read the datasheet. Q. I want to protect my circuit from overcurrents and shorts. A. Get a polyswitch, available from, among others, the manufacturer RayChem. See http://www.raychem.com/, search for miniSMDC075. These are tiny autoresetting fuses that limit the current to no more than a certain value. Q. How do I save power in my embedded micro system? A. There are many methods to reduce the power consumption of a circuit with a micro in it. 1. Use the lowest clock frequency possible. For PIC micros, the power consumption seems to rise as the square of the frequency. 2. Put the micro into sleep mode. It can wake itself up when an internal timer rolls over. Be careful to complete all operations, in software and hardware, before putting the micro to sleep. For example, if a serial character is only half received in hardware, wait until it is fully received before shutting down. 3. Switch off external peripherals when they are not in use. For example, have one pin on the micro connected to the standby pin of the serial chip. You could even power external chips off the micro, as the micro can source 20mA, and simply switch off the port when it is not in use. 4. Use the lowest voltage possible. In saying this, be very careful to look up the voltage range for each chip when using it in your circuit. An example is a 5V embedded datalogger, which had a 4Mbit flash chip in it. Instead of using the AT45D041, the 5V part, the AT45DB041, the 3.5V th part, was used. It seemed to work perfectly. The only problem was that every 20 page of data read from the chip was completely corrupted. Q. My PIC sometimes resets by itself. A. Bad power? Brownouts? Put a decoupling cap as close to the power supply as possible, so when it switches it doesnt brown itself out. 0.1uF for <8Mhz, 0.01uF for >8Mhz.

Bootloader for PIC16F876


Q. How do I do a bootloader for the flash based 16F876? A. Although code is available from Hi-Tech, this is a modified and enhanced version that doesnt need RB0 - it uses timeouts, so the code is loaded within 1 second of powerup. It also handles config bits properly, and programs the EEPROM also. See sample code archive here.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

Simple Multitasking Kernel for PIC under Hi-Tech C


Q. How do I handle many things at once on a PIC? I want a simple multitasking system. A. See here for a big explanation of this.

Tips for using the PICSTART Plus Programmer


Q. The programmer doesnt seem to work it doesnt program A. Sometimes this happens, maybe MPLab has got something wrong with it or the programmer itself has crashed. It can crash its running code just like the computer. Pull the plug out of the programmer, shutdown the computer and restart it, then retry it. This usually fixes the problem. Q. How do I embed configuration words for the programmer into my C program Q. MPLab always loses my settings for the PICStart plus programmer when I exit A. Use the __CONFIG(); macro in your C code, after #include<pic.h> to set these bits. First, look up the appropriate include file for your micro. Then compare this to the include bits in the PIC .pdf manual. For the PIC16C76, <pic.h> includes file pic1677.h, found in c:\ht-pic\include\. At the bottom of the file,these lines appear: //look up datasheet for explanation of terms #define CONFIG_ADDR 0x2007 #define FOSC0 0x01 #define FOSC1 0x02 #define WDTE 0x04 //Watch Dog Timer (Enable low) - (include to disable) #define PWRTE 0x08 //PoWeR Up Timer (Enable low) - (include to disable) #define BODEN 0x40 //Brown Out Detect ENable - active HIGH (include to enable) #define RC (FOSC1 | FOSC0) #define HS FOSC1 #define XT FOSC0 #define LP 0x00 #define CP0 0x1510 #define CP1 0x2A20 /* code protection */

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#define #define #define #define

UNPROTECT (CP0 | CP1) // unprotected PROTECT50 CP1 // upper half program memory code protected PROTECT75 CP0 // upper 3/4 program memory code protected PROTECT 0x00 // all memory code is protected

Thus, to make PICStart Plus default to HS, Watchdog On, Power up time enabled, Brown Out Timer enabled, and Unprotected, use the following lines: #include<pic.h> __CONFIG(HS | BODEN | UNPROTECT); Be careful of PWRTE. According to the PIC manual, this is active low, so missing it out turns the power up timer on. Including it turns it off. This is the same for WTDE.

Tips on using Libraries with MPLab


Q. What is a library, consisting of a ".lib" file, and how do I use it? A. Normally, most people have a library of commonly-used routines that are always included in every project they do. For example, there is the following files: delay.c - delay routines in C such as DelayMs(x) delay.h - header file for delay.c serial.c - serial RS232 routines such as putch() and getch() serial.h - header file for serial.c

One method of using these routines could be to include these files in your project. Put the following lines in your main .c file: #include #include #include #include main() { "delay.h" "delay.c" "serial.h" "serial.c"

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

} However, this method has one key disadvantage: even if a routine is not used, it will still take up memory in the final compiled .hex file. Using a library solves this problem. Once you have made a library out of your commonly used routines, the linker picks out the necessary routines and includes them in the final .hex file. Q. How do I make a library file? Lets say I have a number of modules, each one an object file, ending in ".obj". I can put these in a library by executing the following at the dos prompt: libr r xx.lib i2c.obj ser_877.obj delay1.obj I now have a library called xx.lib which can be included in my project. Under 'Project' and 'Edit Project' and the 'Library Path' box, enter the path to xx.lib. If it gives an error, see here. Alternatively, use 'Add Node' to add the ".lib" file to the project. Q. I make a library file ending in ".lib" but I cant tell MPLab how to get to it A. Under Project..Edit Project, click in 'Library Path'. If you see the following error message, you have set up the project incorrectly.

You need install the 3 languages: under "Project..Install Language Tool" for compiler, Assembler and Linker, all select "c:\ht-pic\bin\picc.exe". For a more complete explanation or this, see here. Select "Project..New project (or Edit Project)" then click on "node property" ***[.HEX] : select language tool: Linker

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

***[.C]: select language tool: Compiler If the language tool for ***[.HEX] is set to Compiler, then this means the linker is never used, and no libraries or additional C files can be added. For a complete worked example of how to correctly set up a project, see the tutorial web page here.

Serial Numbers with Hi-Tech C


Q. How do I add serial numbers to a program coded in Hi-Tech C? A. Use the following to preserve the Rom location for a serial number: ;Reserves 4 bytes for Serial Number programming ;To be placed at 0x0FFC to 0x0FFF with the PICC option -L-Ppreserve=ffch ;The 0x0FFF=4096 is for a 4k micro, a 2k or 8k micro would be different psect retlw retlw retlw retlw psect preserve 0xFF ;Serial 0xFF ;Serial 0xFF ;Serial 0xFF ;Serial preserve

No No No No

The "-L-Ppreserve=ffch" must be entered in the option field in MPLAB for the HiTech Linker to place the code segment at the specific address. The code is saved as an *.as file and included as a node in the MBLAB project and uses the PICC Assembler to compile. Remember to set the Assembler in the Language tool to Picc.exe.

Incremental Compiles with Hi-Tech C


Q. Under Hi-Tech C and MPLab, every time I recompile, it recompiles everything and then links it. How do I do incremental compiles? A. Add the line 'c:\ht-pic\include' under 'include path' in the 'edit project' dialogue to enable incremental compiles. You must already have the 'language tool' under the root node set to 'PIC C Linker', not 'PIC C compiler'. Add each source file to the list to be compiled and then linked.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

For instructions on how to set up a project properly to support support libraries, additional C files, and incremental compiles, see here.

The PIC12Cx67x
Q. How do I set the OSCCAL register in Hi-Tech C for the PIC12Cx67x? A. If the built-in 4Mhz RC oscillator for the PIC12Cx67x is used, it can drift with temperature variations. The oscillator calibration speed is trimmed by setting register OSCCAL at run time. The top ROM byte in memory is read to obtain this value at runtime. Looking in the header file, c:\htpic\include\pic1267x.h, we find the following lines, in different parts of the header file static volatile unsigned char bank1 OSCCAL @ 0x8F; #if defined(_12C672) || defined(_12CE674) #define _READ_OSCCAL_DATA() (*(unsigned char(*)())0x7FF)() #endif Thus, use the following C line at the start of the program: OSCCAL=_READ_OSCCAL_DATA(); If you are doing any sort of development, you will be using a UV-erasable JW part. Remember to record the value of the highest ROM address. It will be in the form retfw N where N=calibration value. For example, if N=0x90, the instruction will be 0x3490. I used seven PIC12C672-JW parts in development. The OSCCAL values that I recorded for them were 0x90, 0x94, 0xB0, 0x84, 0xC8, 0xB0, 0xC0. This illustrates the fact that there is process variation among batches of PIC micros. If you lose the value of OSCCAL for a particular JW part, you can retrieve it, with effort. Write a little routine to output 10kHz pulses. Alter the OSCCAL value until the pulses are indeed 10kHz as viewed on an oscilloscope.

We welcome any suggesions or comments! Send them to shane@workingtex.com. Huge FAQ plus sample code from home page at http://www.workingtex.com/htpic/ Legally, all code snippets taken from this site must include a link back to this site.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

All code on this site is free for non-commercial use. If you are using any code from this site in a commercial situation contact shane@workingtex.com for licence information. All content on this site created by Shane Tolmie is copyrighted by Shane Tolmie (c) 2001. For PIC micro consultancy services http://www.workingtex.com/consult/

PIC and Hi-Tech C Archive Q. How do I handle many things at once on a PIC?
A. Go to http://www.pumpkininc.com/ Look at their 'Salvo' real time operating system. The quote below says it all. " ... I use this system for near on 2 years and I can tell only the best things for it (even I can say that my life like PIC programmer has 3 periods - assembler, HiTech C and RTOS SALVO - the difference between assembler and C is the same like between no RTOS and RTOS)." - Luben Christov Neither the author of this web page nor Luben Christov have any affiliation with PumpkinInc - but we both share a liking for it! See also http://www.bknd.com/cc5x/multitasking.shtml for a discussion on multitasking and state machines. I wrote the rest of the document below before I came across Salvo. The technique works nicely enough, but Salvo is has far superior power. A. Alternatively, use a State Machine or Time sliced multi-tasking system

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

A state machine is recommended for most solutions where there is non time-critical tasks to perform. However, the time sliced multi-tasking is useful when:

1. There is multiple tasks. 2. Some of the tasks are low-priority, and can execute in the background, being interrupted by higher priority tasks. For example, lowfrequency PWM with 300ms of mathematical calculations happening every 1 second. Using a State Machine The topic of this tutorial is not to teach state machines - they are very common - look them up on the web. Using a Time Sliced Multi-tasking system The multitasking system below was used to implement, on an 8-pin 12CE674 and 28-pin 16F876, software polling of a pin to get serial characters, perform maths at regular intervals on the serial character buffer, write the data to a 24LC256 I2C EEPROM, and generate 50Hz variable duty cycle PWM. This was all performed simultaneously, so the PIC could accept a continuous serial stream. It works beautifully - the code is stable. Heres the explanation of how this was achieved. This technique that allows one to harness the power of a PIC micro. It is definitely worth learning, and probably the single most important technique in this FAQ.

1. 2. 3. 4.

5. 6.

For this example, set up the simulator for a PIC16F876. Set up timer 1 to overflow and trigger and generate an interrupt every 500us. The interrupt service routine will get executed every 500us. For each individual task, have three things: i. A counter that increments every time the interrupt happens every 500us ii. A task counter maximum, called TASKX_COUNTER_MAX. When the counter gets to this maximum, it executes the task. Thus, one can set the frequency that each task gets performed by changing this maximum. One task may have a maximum set to 1, which means it executes every 500us, and another set to 2000 which means it only gets executed every 1000ms. iii. A task enable boolean flag, TASKX_ENABLE. Thus, we can set the frequency and priority of how often each task gets performed. We can extend this further what happens if we have to regularly do a task that takes ages, say 100ms of mathematical calculations, but it only happens every second? It we execute it right in the interrupt, it will stop all the high frequency, important tasks from executing every 500us. We couldnt have the PWM stopping for 100ms. 1. So, all we do is trigger the slow, complex task from the interrupt, by setting taskX_go=true. Then, the interrupt immediately finishes ready for the next task.

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

2. In the meantime, a loop in main() is polling taskX_go. If it is true, it sets it to false ready for next time, then executes the task at its
leisure. While this is going on, the high priority tasks still happen at a normal rate.

7. In summary: 1. We can execute any number of tasks at regular intervals. 2. We can choose the frequency of executing each task by altering TASKX_COUNTER_MAX. 3. Choose the order of execution by having the most important tasks first in the interrupt routine. This alters the priority. 4. Have slow, infrequent background tasks executing in main(), triggered by the interrupt setting taskX_go=true at regular intervals. 8. There is one more tip to avoid problems. The time inbetween the 500us ticks must be enough to execute all the tasks, in the worst case.
Either that, or only one task is executed per 500us interrupt tick, and the others have to wait until a free slot comes along. To tell whether the timing is too tight and tasks are executed again before the previous one had a chance to finish, add a line to check whether the timer interrupt flag has aleady been set before the interrupt exits. Download Complete Example Project For a sample project illustrating this time-sliced method, follow this link. View Plans. Sample Code Outline The sample code below briefly outlines the code described above: //(c)Shane Tolmie, http://www.workingtex.com/htpic/, distribute freely for non commercial use, you must include this comment. //***** //multitasking system handle multiple tasks with one microprocessor //task counters used to tell when a task is ready to be executed //all these counters are incremented every time a 500us interrupt happens //every task has its own counter that is updated every time a 500us interrupt happens unsigned int task0_counter=0; unsigned int task1_counter=0; unsigned int task2_counter=0; //this tells when a task is going to happen again //for example, when task0_counter==TASK0_COUNTER_MAX, set task0_counter=0 and do task #define TASK0_COUNTER_MAX 1 //high frequency task every 500us, maybe PWM

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

#define TASK1_COUNTER_MAX 2000 #define TASK2_COUNTER_MAX 5000

//low frequency task every 1000ms //low frequency and low priority task, every 2500ms

//Note: every variable referenced in both interrupt and main() must be declared volatile. You have been warned! //this enables/disables a task volatile unsigned char task0_enable=TRUE; volatile unsigned char task1_enable=TRUE; volatile unsigned char task2_enable=TRUE; //this allows tasks triggered by interrupt to run in the background in main() volatile unsigned char task2_go=FALSE; void setup_multitasking(void) { //set up tmr1 to interrupt every 500us TMR1CS=0; T1CKPS0=0; T1CKPS1=0; /*We want to wait 2000 clock cycles, or 500us @ 16MHz (instructions are 1/4 speed of clock). Timer 1 interrupts when it gets to 0xFFFF or 65535. Therefore, we set timer 1 to 65535 minus 2000 = 63535, then wait 2000 ticks until rollover at 65535. To test, use simulator to find that its exactly correct*/ #define TICKS_BETWEEN_INTERRUPTS 2000 #define INTERRUPT_OVERHEAD 19 #define TMR1RESET (0xFFFF-(TICKS_BETWEEN_INTERRUPTS-INTERRUPT_OVERHEAD)) #define TMR1RESET_HIGH TMR1RESET >> 8 #define TMR1RESET_LOW TMR1RESET & 0xFF TMR1ON=0; TMR1H=TMR1RESET_HIGH; TMR1L=TMR1RESET_LOW; TMR1ON=1; TMR1IF=0; TMR1IE=1; PEIE=1; GIE=1; }

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

void interrupt isr(void) { //one tick every 500us at 16Mhz if (TMR1IF) { //set up timer 1 again to interrupt 500us in future TMR1IF=0; TMR1ON=0; TMR1H=TMR1RESET_HIGH; TMR1L=TMR1RESET_LOW; TMR1ON=1; task0_counter++; if (task0_counter>=TASK0_COUNTER_MAX) //high frequency task every 1 tick { task0_counter=0; if (task0_enable==TRUE) { //do high frequency important task 0, for example PWM } } task1_counter++; if (task1_counter>=TASK1_COUNTER_MAX) //low priority task - every 2000 ticks { task1_counter=0; if (task1_enable==TRUE) { //do low frequency yet important task 1 } } /*this task takes a long time, 100ms for example, lots of maths. Is extremely low priority, but has to be done at regular intervals, so all this does is trigger it. In main(), it will, at leisure, poll task2_go and then execute it in the background.*/ task2_counter++; if (task2_counter>=TASK2_COUNTER_MAX) {

//every 250ms

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

task2_counter=0; if (task2_enable==TRUE) { //every 250ms take 100ms to do maths, do this in main() so the we can get back to doing the high frequency tasks. task2_go=TRUE; } } } //if (TMR1IF) } //interrupt routine main() { setup_multitasking(); while(1) { if (task2_go==TRUE) { task2_go=FALSE; //take our time, doing heaps of complex maths at our leisure in the background } } }

We welcome any suggesions or comments! Send them to shane@workingtex.com. Huge FAQ plus sample code from home page at http://www.workingtex.com/htpic/ Legally, all code snippets taken from this site must include a link back to this site. All code on this site is free for non-commercial use. If you are using any code from this site in a commercial situation contact shane@workingtex.com for licence information. All content on this site created by Shane Tolmie is copyrighted by Shane Tolmie (c) 2001. For PIC micro consultancy services http://www.workingtex.com/consult/

This document is created using PDFmail (Copyright RTE Software) http://www.pdfmail.com

S-ar putea să vă placă și