increment casted void pointer -- ANSI?

John F. Woods jfw at ksr.com
Sat Mar 9 04:15:49 AEST 1991


berg at marvin.e17.physik.tu-muenchen.de (Stephen R. van den Berg) writes:
>Suppose I have the following (silly example, I know :-) program:
>main(){static char s[]="abcd";void*p;int a,b;
> p=s;
> a=*(char*)p;
> b=*++(char*)p;
> *--(char*)p=b;
> *++(char*)p=a;
> puts(s);
> return 0;}
>Now, you tell me if this is ANSI or K&R or neither,

Neither.  The operand of ++ and -- must be an lvalue; the result of a
cast is an rvalue.

>how do I do it in ANSI then?

Leaving in the "silliness" to make the conceptual changes more clear:

main(){
	static char s[]="abcd";
	void*p;
	char *cp;	/* added */
	char a,b;	/* changed */
	p=s;
	cp = p;		/* added; note that void pointers are not objects
			 * you DO things with; they are typeless bags
			 * for data-pointers which should be assigned to
			 * a correctly-typed pointer for real work.
			 */
	a = *cp;	/*changed*/
	b = *++cp;	/*changed*/
	*--cp = b;	/*changed*/
	*++cp = a;  	/*changed*/
	puts(s);
	return 0;
}

By the way, 
	b = cp[0];
	cp[0] = cp[1];
	cp[1] = b;

is not only clearer, but stands a good chance of running as fast or faster.
Try compiling to assembly code and counting cycles.
Array notation is NOT evil or inefficient.



More information about the Comp.lang.c mailing list