Casting a postdecrement operand

Wayne Throop throopw at dg_rtp.UUCP
Sun Jun 1 07:34:16 AEST 1986


> greg at utcsri.UUCP (Gregory Smith)
>> lwh at romp.UUCP (lwh)

>>My version of pcc on the IBM RT PC allows the following expression:
>>                ((struct abc *)cbap)++;
>>to increment cbap by 500. It appears that the ANSI standard doesn't say
>>anything about the legality of this syntax.  

Well, no.  It says that the *syntax* is legal.  The *semantics* of such
an increment are explicitly outlawed.  A cast does *not* mean and
*never* *has* meant to "treat the bits as a new type".  It means
*convert* the bits to the new type, and this conversion is machine
dependant, and *never* results in an lvalue.

> First, a technical point: There is nothing wrong with the `syntax',

Right, right.

> The *semantics*, though, are a different question.

Yes, yes.

> You are saying
> 'Treat cbap as a pointer to a (struct abc); increment that pointer'.

No, no.

That may be what lwh *meant*, but that's not what he *said*.  What he
*said* was to increment a non-lvalue expression.  Just as meaningful as
saying "(i+j)++".  Which is to say, not very meaningful.

> The compiler dutifully adds 500. ( You asked for it, you got it... )

Well, *his* compiler dutifully adds an ammount large enough to reach the
next (struct abc), which on his machine happens to be 500.  Rephrasing,
there are two interesting issues here.  First, the fact that the
compiler allows a cast to be used as an lvalue is bogus in the first
place.  That compiler, quite simply, allowed an illegal operation.  In
the second place, performing the increment-by-1 operation on a (struct
abc *) is a machine-dependant operation, which on lwh's machine happens
to change the pointer's bit-pattern in such a way that, if that bit
pattern had been a twos-complement integer, we would have said it was
incremented by 500.  As I say, machine dependant to the max.

> This is perfectly legal, but lint might well want to prod you about it...

It is *not* legal, perfectly or imperfectly.  And lint *had* *better*
prod you about it.  (It does, by the way.  It says "illegal lhs of
assignment".)

> Since you are explicitly casting the pointer, though, it should be plain
> that you have good reasons to do so.

As may be.  But once you have cast the pointer, you cannot use the cast
expression as an lvalue.  K&R say this is illegal, Harbison and Steele
say this is illegal, and the ANSI draft says this is illegal.  I mean,
when the Father, the Son, and the Holy Ghost say it's illegal, I say it
is then, now, and evermore, *ILLEGAL*.
-- 
Wayne Throop      <the-known-world>!mcnc!rti-sel!dg_rtp!throopw



More information about the Comp.lang.c mailing list