type cast in initializer

Doug Gwyn <gwyn> gwyn at brl-tgr.ARPA
Sun Feb 2 09:41:20 AEST 1986


> > I've found the two lines
> > 
> > 	int	x = 0;
> > 	char	*ptr = (char *) &x;
> > 
> > acceptable to every C compiler I've used, until running into the
> > Whitesmith's C compiler.  They refuse to accept the type coercion "(char *)"
> > on the second initialization.  As I read K&R this should be acceptable
> > through the rules
> 
> The posting did not indicate whether the variables are static or auto.

The variables cannot be static, with those declarations.  I assume you
mean, file scope vs. block scope.  In any case, it doesn't matter; the
example is valid C code.  (However, I wonder what it was trying to do.
Treating the address of an int as a (char *) is rarely required, with
fread/fwrite buffer parameter being the only common occurrence.)

> The initializer should be legal if x is static, but not neccesarily if
> x is declared as an auto.  If x is auto, the compiler could place it in
> a register whose address cannot be taken.

That would be a compiler bug.  Also, the presence or absence of the type
cast would surely be irrelevant in such a case.

> The compiler should be smart enough to notice the address operator and
> disallow register allocation.  K&R only states that variables declared
> register cannot have their address taken.  Anyone know what ANSI says?

"The operand of the unary & operator must be a function locator or an
lvalue that designates an object other than a bit-field or an object
declared with the `register' storage-class specifier."



More information about the Comp.lang.c mailing list