Question 1.1
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-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
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
Question 1.4
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
Question 1.7
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 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
Question 1.11
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. 75-6
Question 1.12
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
Question 1.14
I can't seem to define a linked list successfully. I tried
typedef struct {
char *item;
NODEPTR next;
} *NODEPTR;
but the compiler gave me error messages. Can't a structure in C contain 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. 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
Question 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:
1. char *(*(*a[N])())();
2. Build the declaration up incrementally, using typedefs:
typedef char *pc; /* pointer to char */
typedef pc fpc(); /* function returning pointer to char */
typedef fpc *pfpc; /* pointer to above */
typedef pfpc fpfpc(); /* function returning... */
typedef fpfpc *pfpfpc; /* pointer to... */
pfpfpc a[N]; /* 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).
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. 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
Question 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.
Question 1.25
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
Question 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?
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
Question 1.31
This code, straight out of a book, isn't compiling:
f()
{
char a[] = "Hello, world!";
}
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 the array won't be written to). (You can always initialize local char * variables
to point to string literals, but see question 1.32.) 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.
Question 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 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
Question 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 question 4.12.
Question 2.1
What's the difference between these two declarations?
struct x1 { ... };
typedef struct { ... } x2;
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.
Question 2.2
Why doesn't
struct x { ... };
x thestruct;
work?
C is not C++. Typedef names are not automatically generated for structure tags. See also question
2.1.
Question 2.3
Can a structure contain a pointer to itself?
Most certainly. See question 1.14.
Question 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.
Question 2.6
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?
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 interpretation of the Standard as well.
References: Rationale Sec. 3.5.4.2
Question 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. [footnote]
(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
Question 2.8
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
Question 2.9
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, compilersupplied
``hidden'' argument to the function. Some older compilers used a special, static location
for structure returns, although this made structure-valued functions non-reentrant, which ANSI C
disallows.
References: ANSI Sec. 2.2.3
ISO Sec. 5.2.3
Question 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 structure-building function; see question 14.11 for an example. (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.
Question 2.11
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 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 human-readable) way.
References: H&S Sec. 15.13 p. 381
Question 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
Question 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.
References: H&S Sec. 5.6.7 pp. 139-40
Question 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 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
Question 2.15
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;
Question 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 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
Question 2.20
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
Question 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.)
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
ANSI Sec. 3.1.2.5, Sec. 3.5.2, Sec. 3.5.2.2, Appendix E
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
Question 2.24
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.)
Question 3.1
Why doesn't this code:
a[i] = i++;
work?
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.)
References: K&R1 Sec. 2.12
K&R2 Sec. 2.12
ANSI Sec. 3.3
ISO Sec. 6.3
Question 3.2
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?
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 Sec. 3.3
ISO Sec. 6.3
CT&P Sec. 3.7 p. 47
PCS Sec. 9.5 pp. 120-1
Question 3.3
I've experimented with the code
int i = 3;
i = i++;
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?
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.)
Question 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
Question 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
Question 3.8
How can I understand these complex expressions? What's a ``sequence point''?
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 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.
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
Question 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.
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.
Question 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.
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
Question 3.14
Why doesn't the code
int a = 1000, b = 1000;
long int c = a * b;
work?
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 floatingpoint
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
Question 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;
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
Question 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);
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
Question 4.3
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. 199-200
Question 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?
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 pcc-derived 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
Question 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;
f(ip);
the pointer in the caller remains unchanged.
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.
Question 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 *.
Question 4.10
I have a function
extern int f(int *);
which accepts a pointer to an int. How can I pass a constant by reference? A call like
f(&5);
doesn't seem to work.
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.
Question 4.11
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
Question 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, 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
Question 5.1
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 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).
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
Question 5.2
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);
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: Explicit cast required:
initialization function call,
no prototype in scope
assignment
variable argument in
comparison varargs function call
function call,
prototype in scope,
fixed argument
References: K&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
Question 5.3
Is the abbreviated pointer comparison ``if(p)'' to test for non-null 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)
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 (expr)?0:1
or to ((expr) == 0)
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
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
Question 5.4
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
Question 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 ((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
Question 5.6
If NULL were defined as follows:
#define NULL ((char *)0)
wouldn't that make function calls which pass an uncast NULL work?
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)
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
Question 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 non-pointer contexts.) In particular, do not use
NULL when the ASCII null character (NUL) is desired. Provide your own definition
#define NUL '\0'
if you must.
References: K&R1 Sec. 5.4 pp. 97-8
K&R2 Sec. 5.4 p. 102
Question 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.
Question 5.12
I use the preprocessor macro
#define Nullptr(type) (type *)0
to help me build null pointers of the correct type.
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.
Question 5.13
This is strange. NULL is guaranteed to be 0, but the null pointer is not?
When the term ``null'' or ``NULL'' is casually used, one of several things may be meant:
1. 1. The conceptual null pointer, the abstract language concept defined in question 5.1. It is
implemented with...
2. 2. The internal (or run-time) representation of a null pointer, which may or may not be allbits-
0 and which may be different for different pointer types. The actual values should be
of concern only to compiler writers. Authors of C programs never see them, since they
use...
3. 3. The null pointer constant, which is a constant integer 0 (see question 5.2). It is often
hidden behind...
4. 4. The NULL macro, which is #defined to be 0 or ((void *)0) (see question 5.4). Finally,
as red herrings, we have...
5. 5. The ASCII null character (NUL), which does have all bits zero, but has no necessary
relation to the null pointer except in name; and...
6. 6. 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...
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.
Question 5.14
Why is there so much confusion surrounding null pointers? Why do these questions come up so
often?
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) is often overlooked.
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 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.
Question 5.15
I'm confused. I just can't understand all this null pointer stuff.
Follow these two simple rules:
1. When you want a null pointer constant in source code, use ``0'' or ``NULL''.
2. If the usage of ``0'' or ``NULL'' is an argument in a function call, cast it to the pointer type
expected by the function being called.
The rest of the discussion has to do with other people's misunderstandings, 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.
Question 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 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, the urge to assume an
internal zero representation would not even arise.)
Question 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 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
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-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
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
Question 1.4
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
Question 1.7
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 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
Question 1.11
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. 75-6
Question 1.12
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
Question 1.14
I can't seem to define a linked list successfully. I tried
typedef struct {
char *item;
NODEPTR next;
} *NODEPTR;
but the compiler gave me error messages. Can't a structure in C contain 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. 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
Question 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:
1. char *(*(*a[N])())();
2. Build the declaration up incrementally, using typedefs:
typedef char *pc; /* pointer to char */
typedef pc fpc(); /* function returning pointer to char */
typedef fpc *pfpc; /* pointer to above */
typedef pfpc fpfpc(); /* function returning... */
typedef fpfpc *pfpfpc; /* pointer to... */
pfpfpc a[N]; /* 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).
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. 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
Question 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.
Question 1.25
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
Question 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?
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
Question 1.31
This code, straight out of a book, isn't compiling:
f()
{
char a[] = "Hello, world!";
}
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 the array won't be written to). (You can always initialize local char * variables
to point to string literals, but see question 1.32.) 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.
Question 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 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
Question 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 question 4.12.
Question 2.1
What's the difference between these two declarations?
struct x1 { ... };
typedef struct { ... } x2;
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.
Question 2.2
Why doesn't
struct x { ... };
x thestruct;
work?
C is not C++. Typedef names are not automatically generated for structure tags. See also question
2.1.
Question 2.3
Can a structure contain a pointer to itself?
Most certainly. See question 1.14.
Question 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.
Question 2.6
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?
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 interpretation of the Standard as well.
References: Rationale Sec. 3.5.4.2
Question 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. [footnote]
(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
Question 2.8
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
Question 2.9
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, compilersupplied
``hidden'' argument to the function. Some older compilers used a special, static location
for structure returns, although this made structure-valued functions non-reentrant, which ANSI C
disallows.
References: ANSI Sec. 2.2.3
ISO Sec. 5.2.3
Question 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 structure-building function; see question 14.11 for an example. (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.
Question 2.11
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 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 human-readable) way.
References: H&S Sec. 15.13 p. 381
Question 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
Question 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.
References: H&S Sec. 5.6.7 pp. 139-40
Question 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
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 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
Question 2.15
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;
Question 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 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
Question 2.20
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
Question 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.)
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
ANSI Sec. 3.1.2.5, Sec. 3.5.2, Sec. 3.5.2.2, Appendix E
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
Question 2.24
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.)
Question 3.1
Why doesn't this code:
a[i] = i++;
work?
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.)
References: K&R1 Sec. 2.12
K&R2 Sec. 2.12
ANSI Sec. 3.3
ISO Sec. 6.3
Question 3.2
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?
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 Sec. 3.3
ISO Sec. 6.3
CT&P Sec. 3.7 p. 47
PCS Sec. 9.5 pp. 120-1
Question 3.3
I've experimented with the code
int i = 3;
i = i++;
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?
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.)
Question 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
Question 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
Question 3.8
How can I understand these complex expressions? What's a ``sequence point''?
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 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.
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
Question 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.
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.
Question 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.
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
Question 3.14
Why doesn't the code
int a = 1000, b = 1000;
long int c = a * b;
work?
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 floatingpoint
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
Question 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;
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
Question 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);
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
Question 4.3
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. 199-200
Question 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?
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 pcc-derived 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
Question 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;
f(ip);
the pointer in the caller remains unchanged.
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.
Question 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 *.
Question 4.10
I have a function
extern int f(int *);
which accepts a pointer to an int. How can I pass a constant by reference? A call like
f(&5);
doesn't seem to work.
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.
Question 4.11
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
Question 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, 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
Question 5.1
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 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).
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
Question 5.2
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);
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: Explicit cast required:
initialization function call,
no prototype in scope
assignment
variable argument in
comparison varargs function call
function call,
prototype in scope,
fixed argument
References: K&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
Question 5.3
Is the abbreviated pointer comparison ``if(p)'' to test for non-null 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)
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 (expr)?0:1
or to ((expr) == 0)
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
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
Question 5.4
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
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
Question 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 ((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
Question 5.6
If NULL were defined as follows:
#define NULL ((char *)0)
wouldn't that make function calls which pass an uncast NULL work?
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)
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
Question 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 non-pointer contexts.) In particular, do not use
NULL when the ASCII null character (NUL) is desired. Provide your own definition
#define NUL '\0'
if you must.
References: K&R1 Sec. 5.4 pp. 97-8
K&R2 Sec. 5.4 p. 102
Question 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.
Question 5.12
I use the preprocessor macro
#define Nullptr(type) (type *)0
to help me build null pointers of the correct type.
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.
Question 5.13
This is strange. NULL is guaranteed to be 0, but the null pointer is not?
When the term ``null'' or ``NULL'' is casually used, one of several things may be meant:
1. 1. The conceptual null pointer, the abstract language concept defined in question 5.1. It is
implemented with...
2. 2. The internal (or run-time) representation of a null pointer, which may or may not be allbits-
0 and which may be different for different pointer types. The actual values should be
of concern only to compiler writers. Authors of C programs never see them, since they
use...
3. 3. The null pointer constant, which is a constant integer 0 (see question 5.2). It is often
hidden behind...
4. 4. The NULL macro, which is #defined to be 0 or ((void *)0) (see question 5.4). Finally,
as red herrings, we have...
5. 5. The ASCII null character (NUL), which does have all bits zero, but has no necessary
relation to the null pointer except in name; and...
6. 6. 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...
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.
Question 5.14
Why is there so much confusion surrounding null pointers? Why do these questions come up so
often?
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) is often overlooked.
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 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.
Question 5.15
I'm confused. I just can't understand all this null pointer stuff.
Follow these two simple rules:
1. When you want a null pointer constant in source code, use ``0'' or ``NULL''.
2. If the usage of ``0'' or ``NULL'' is an argument in a function call, cast it to the pointer type
expected by the function being called.
The rest of the discussion has to do with other people's misunderstandings, 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.
Question 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 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, the urge to assume an
internal zero representation would not even arise.)
Question 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 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
Comments