When is a cast not a cast?

Mark A Terribile mat at mole-end.UUCP
Thu May 4 17:14:50 AEST 1989


> I wanted to be a 'good little programmer' and make all the types
> match up, so I was using casts wherever a promotion might be
> non-obvious.  ...

(Enter flame mode.)
AAAaaaarrrgggghhh!  This is not FORTRAN II.  Mixed mode is supported!  If you
are going to scatter the code with casts, we might as well go back to assembler
so that you can write the conversion instructions ...  For portability, we can
use MIX-MASTER.
(Exit flame mode.)

> 3	char *c;
> 5	int i;
> 10 	p = (c + (char *) i);  /* More trouble than it's worth... */
 
> wherupon both the lint(1) and cc(1) in my Ultrix 2.2 piped-up with
> warnings that the 'operands of + have incompatible types' on line 10...

They sure do.
 
> How can two things explicitly identifiable as being the same type
> (one by declaration, the other by that all-powerful fiat, the cast)
> be suddenly 'incompatible'?

To take the example of FORTRAN (an example which is probably brain-damaged
and which MIGHT have been fixed in -77), you cannot write

	LOGICAL FLAG1, FLAG2

		. . .

	IF( FLAG1 .EQ. FLAG2 ) . . .
 

> I have an inkling as to what I'm missing, ... It involves getting the integer
> quantity (i * sizeof(char *)) . . .

No, No, NO, NO!  C does that for you.  See section A6.6 in K&R-II, or Appendix
A, 7.4, in K&R-I .

...  which leaves one right back in the pigpen wondering how to cast this
> greater integer as in 

> 	p = (c + (char *)( i * sizeof(char *) );

What, praythee tell WHAT, is this meant to do?

Let's look at plain old analytic geometry for a moment.  You can multiply a
scalar times a scalar.  You can multiply a scalar by a vector.  ``Multiplying''
a vector by a vector is an entirely different thing; there are two kinds, but
neither corresponds to the multiplication permitted between a scalar and a
vector.

> I get the feeling that one isn't allowed pointer arithmetic at all.
> It only seems to allow such things as " &(foo[bar]) - foo ", where it
> is 100% certain that both operands point to the same data segment.

See the above-mentioned sections to determine just what operations are
defined and just what they are defined as.  There are really good and useful
operations defined with meaningful sets of operators.  What you've written
above is not a member of the sets of operations/operators that C defines.

C allows the addition of integers to pointers; informally, the result is
a pointer of the type of the original pointer, but offset from the original
by an amount scaled by the size of the object.

>  - I haven't checked it on other compilers.
> 
> 				--Blair

I hope that the other compilers respond in about the same way.
-- 

(This man's opinions are his own.)
>From mole-end				Mark Terribile



More information about the Comp.lang.c mailing list