Expert C Programming

(Jeff_L) #1

p = N sizeof q;


Quickly now, are there two multiplications or only one? Here's a hint: the next statement is:


r = malloc( p );


The answer is that there's only one multiplication, because sizeof is an operator that here takes as its


operand the thing pointed to by q (i.e., *q). It returns the size in bytes of the type of thing to which q


points, convenient for the malloc function to allocate more memory. When sizeof 's operand is a type
it has to be enclosed in parentheses, which makes people wrongly believe it is a function call, but for a
variable this is not required.


Here's a more complicated example:


apple = sizeof (int) * p;


What does this mean? Is it the size of an int, multiplied by p? Or the size of whatever p points at, but
cast to an int? Or something even weirder? The answer isn't given here, because part of being an
expert programmer is learning to write little test programs to probe questions like this. Try it and see!


The more work you make one symbol do, the harder it is for the compiler to detect anomalies in your
use of it. It's not just the kind of people who sing along with the Tiki birds at Disneyland who have
trouble here. C does seem to be a little further out on the ragged edge of token ambiguity than most
other languages.


"Some of the Operators Have the Wrong Precedence"


You know that you've definitely found a problem when the authors of the original report on C tell you
that "some of the operators have the wrong precedence", as Kernighan and Ritchie mention on page 3
of The C Programming Language. Despite this admission, there were no changes in the precedence of
operators for ANSI C. It's not surprising; any change in precedence would have imposed an
intolerable burden on the existing source base.


But which C operators specifically have the wrong precedence? The answer is "any that appear
misleading when you apply them in the regular way." Some operators whose precedence has often
caused trouble for the unwary are shown in Figure 2-1.


Figure 2-1. Precedence Problems of C Operators
Free download pdf