pointer increment
Chris Torek
chris at mimsy.UUCP
Wed Aug 16 23:31:43 AEST 1989
In article <829 at ruso.UUCP> wolfgang at ruso.UUCP (Wolfgang Deifel) writes:
>If you want to increment ptr only by one [byte] you should use a cast.
>
> ((char*)ptr)++ ;
>or
> ((char*)ptr) + 1 ;
The former is illegal: the result of a cast is an rvalue (thing that
goes on the right of an `=' sign), not an lvalue (thing that goes on
the left). ++ may only be applied to lvalues. Many compilers simply
got this wrong; at least one (gcc) allows it as an `extension', although
it is not clear to me what gcc might do with it on a machine in the
DG MV series, where a cast from (int *) to (char *) generates a
shift-and-mask sequence (possibly an efficient one; this one is
for demonstration purposes):
/* char *cp; int *ip; cp = (char *)ip; more(); */
load reg1,-4(frame) // fetch ip
lsh #1,reg1 // shift it left
store reg1,-8(frame) // and store in ip
call more_
Perhaps on such a machine, gcc might compile `((char *)ip)++' as
load reg1,-4(frame) // fetch ip
lsh #1,reg1 // shift it left
call more_
thus incrementing a temporary by one and then discarding the result.
(If gcc maps `((cast)(lvalue))++' internally to `{temp = lvalue;
lvalue = (cast)lvalue + 1; resultis temp;}', it would do something
a bit more reasonable---in the example I am thinking of, it would
result in incrementing the word-pointer ip by zero. Word-pointers
on many machines simply cannot point to a byte within a word. The
byte number, carried around in character pointers, is irrelevant
to the machine instructions that deal with words, and must be discarded
---in this example, by shifting right one bit.)
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain: chris at mimsy.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list