& operator

west at sdcsla.UUCP west at sdcsla.UUCP
Sat Dec 17 13:27:54 AEST 1983


<<<no bugs here>>>

Dave Olson (fortune!olson) said:

	    char *in, *out, buf[];
	    in = buf;
	    out = &(*in++);
    Given the parentheses, out SHOULD be set buf+1; that is, 'in' is
    incremented BEFORE the & operator is applied.

    (The original article did not include the second line of my example,
    and asked whether out should be set to 'in', or 'in+1'.  The answer
    is of course 'in'.  The question is not meaningful as stated.  The
    question should be: does it point to the ORIGINAL value of 'in', or
    the incremented value of 'in'.)
-------------< end quote > --------------

Referring to pages 48 & 91 of Kernighan & Ritchie (or 185-187), we
note that "++" and "*" are of equal precedence, but are evaluated
right-to-left.   So `in' should be incremented, and then what it
now points to should be ``looked at'', and then that address should
be taken and put into `out' ==> thus `out' gets loaded with the
incremented value of `in'.   The parentheses are superfluous.

So I tried it out and discovered that both 4.1c and 4.2 compilers
(Vax and Sun [68000]) disagreed with me.   Given the program:

    #include <stdio.h>
    char *in, *out, buf [ ] = "This string";
    main ()
    {
	    in = buf;          printf ( "in = %X\n", in );
	    out = &(*in++);    printf ( "in = %X, out = %X\n", in, out );
	    out = &*in++;      printf ( "in = %X, out = %X\n", in, out );
	    out = &*(in++);    printf ( "in = %X, out = %X\n", in, out );
    };

However, the results on both Vax and Sun went like this:
    in = 10004
    in = 10005, out = 10004
    in = 10006, out = 10005
    in = 10007, out = 10006

and so my original analysis is WRONG, too.   The reason can be found
on page 187 of K&R:
	``When postfix ++ is applied to an lvalue the result is the
	  value of the object referred to by the lvalue.  After the
	  result is noted, the object is incremented...''

Apparently, "After the result is noted" means after the statement is
evaluated, so parentheses don't matter.   `in' keeps its old value
until after the statement is finished.

			-- Larry West   UC San Diego
possible net addresses:
			-- ARPA:	west at NPRDC
			-- UUCP:	ucbvax!sdcsvax!sdcsla!west
			--	or	ucbvax:sdcsvax:sdcsla:west



More information about the Comp.lang.c mailing list