casts and assignments

Chris Torek chris at mimsy.umd.edu
Fri Dec 1 19:20:42 AEST 1989


In article <6589 at arcturus> evil at arcturus.UUCP (Wade Guthrie) writes:
>... I am led to believe that all assignments include an implicit cast
>such that:
>	a = (type of 'a') (expression);
>Is exactly equivalent in ALL cases to:
>	a = (expression);
>Is this true?

Almost.  The result will always be the same [but see below]; however, the
assignment without the cast may be illegal:

	long l;
	char *cp;
	...
	l = cp;		/* should produce at least a warning */
	l = (long)cp;	/* implementation defined, typically no warning */

The result of a cast is (semantically) the same as the result of an
assignment to an unnamed temporary variable with the type given by the
cast, hence

	l = (long)cp;

really means:

	long unnamed_temporary = cp;
	l = unnamed_temporary;

and since both the unnamed temporary and l are long, the assignment is
(probably) just a bit-for-bit copy.  Some simple optimisation will
turn even this (silly) approach into an assignment from cp directly into
l.

One could, however, imagine a machine with the following properties:

	0. there is a -0
	1. there is a valid pointer whose `int' value is -0
	2. copying an int from one register to another with
	   a `move integer' instruction replaces -0 with 0 in
	   the destination.

Then, if the compiler were to do something stupid for

	i = (int)cp;

and generate the sequence

	move pointer cp -> temporary
	move integer temporary -> i

while using the sequence

	move pointer cp -> i

for `i = cp;', the resulting value would be different for the two
assignments.  I am not sure that this is legal, nor am I sure it is
illegal.  It is certainly unlikely.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list