type cast in initializer

Gary Ansok ansok at spp3.UUCP
Sat Feb 8 09:15:55 AEST 1986


>	int	x = 0;
>	char	*ptr = (char *) &x;

Even if the pointers (int *) and (char *) have different formats,
the assignment should take care of the conversion, so the cast should
be unnecessary.  A cast in an assignment var_1 = (type) var_2 is never
strictly necessary, except for readability (a good reason!), to keep
lint happy, or to work around bad compilers.  (The cast *should* be
acceptable to the compiler, though).  As I understand it, a cast has
the effect of an assignment to a temporary unnamed variable;
sqrt((double) i) is equivalent to (tmp_double = i, sqrt(tmp_double)).

Are there any other cases where casts are NEEDED besides:

	function calls:  doub_var = sqrt((double) int_var);
	pointer punning: long_var = *(long *) char_ptr;

Note: that last example is NONportable and downright dangerous
on machines with alignment requirements.  Still, it gets used
by a lot of programmers (including me, on occasion...sigh).

			Gary Ansok
			{ihnp4,ucbvax,decvax}!trwrb!trwspp!spp3!ansok



More information about the Comp.lang.c mailing list