The sizeof operator

page 135

This may seem like an excessively roundabout or low-level way of finding the number of elements in an array, but it is the way it's done in C, and it's perfectly safe and straightforward once you get used to it. (I would, however, be hard-pressed to defend against the accusation that it's a bit too low-level.)

Note that sizeof works on both type names (things like int, char *, struct key, etc.) and variables (strictly speaking, any expression). Parentheses are required when you're using sizeof with a type name and optional when you're using it with a variable or expression (just like return), but it's safe to just always use parentheses.

sizeof returns the size counted in bytes, where the C definition of ``byte'' is ``the size of a char.'' In other words, sizeof(char) is always 1. (It turns out that it's not necessarily the case, though, that a byte or a char is 8 bits.) When we start doing our own dynamic memory allocation (which will be pretty soon), we'll always be needing to know the size of things so that we can allocate space for them, so it's just as well that we're meeting and getting used to the sizeof operator now.

The sentence ``But the expression in the #define is not evaluated by the preprocessor'' means that, as far as the preprocessor is concerned, the ``value'' of the macro NKEYS (like the value of any macro) is just a string of characters like

	(sizeof(keytab) / sizeof keytab[0])
which it replaces wherever NKEYS is used, and which will then be evaluated by the compiler as usual, so it doesn't matter that the preprocessor wouldn't have known how to deal with the sizeof operator, or how big the keytab array or a struct key were.

A third way of defining NKEYS would be

	#define NKEYS (sizeof(keytab) / sizeof *keytab)

Note that the definition of NKEYS depends on the definition of the keytab array (which appears on page 133), and both of them will have to precede the use of NKEYS in main on page 134. (Also, all three will have to be in the same source file, unless other steps are taken.)

page 136

Notice that getword has a lot in common with the getop function of the calculator example (section 4.3, page 80).


Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995, 1996 // mail feedback