C compiler weirdness?

Mark Bartelt sysmark at aurora.physics.utoronto.ca
Sat Apr 13 03:59:09 AEST 1991


David Blythe wrote ...

| I recently dug up a copy of the hoc calculator described in kernighan & pike
| only to discover that the C compiler does not increment pc until after the
| function call returns in the following statment:
|                   (*(*pc++))();
| whereas the rest of the program is assuming it is done before the function is
| actually called.  Is the compiler interpretation supposed to be implementation
| dependent?  I would suspect not, but then I can't believe no one else has

... to which Michael Sweet replied ...

| The time of increment/decrement IS compiler dependent.  The only constraint
| with ++/-- is that '++i' increments 'i' before using that value, and 'i--'
| after the valuye is used.  This causes MUCH heartache in the above code and
| the following (which I see all too often, and should NEVER be used if you want
| to port code to a different machine!)
|
|  while (*s)
|   *s = *++s;

Sorry, but this example is irrelevant to the bug being reported (and it is a
bug, if the behaviour of the SGI compiler is in fact what David reports it to
be; I haven't yet confirmed that it is, though I have no reason to doubt that
it is).

It's certainly true that the *s = *++s stuff is a proper example of bad code,
since C "does not specify the order in which the operands of an operator are
evaluated" [K&R-2, 2.12].

However, this has no bearing on David's question.  The critical issue here
is what happens during expression evaluation.  Since the incrementing of an
operand (after noting its value) is part of the definition of the semantics
of the postfix ++ operator, it seems quite clear that postfix incrementing
has to be treated as an atomic operation.  In other words, the operand gets
incremented after its value is noted, but before anything else happens.  K&R
is admittedly a bit vague about this ("After the value is noted, the operand
is incremented ..." [A7.3.4]), but I think it's universally acknowledged that
"after" means "immediately after".  I'm sure that some high-level guru will
correct me if I'm wrong, but I don't think I am.

As a further confirmation that the delay (until after the return from the
function call) in the postincrement of pc is truly a bug, doesn't the fact
that David's example was taken from Kernighan and Pike, coupled with the
fact that bwk is the 'K' in "K&R", suggest something?

Mark Bartelt                                                    416/978-5619
Canadian Institute for                                 mark at cita.toronto.edu
Theoretical Astrophysics                               mark at cita.utoronto.ca



More information about the Comp.sys.sgi mailing list