Fun with numbers - dammit, but I want a cast!

Terry Reedy tjreedy at udel.edu
Mon Aug 11 22:09:52 EDT 2003


"Carl Banks" <imbosol at aerojockey.com> wrote in message
news:yVVZa.764$u%2.33 at nwrdny02.gnilink.net...
> Terry Reedy wrote:
> > No, quite different.  A C cast (at least usually) recasts a block
of
> > bits in a new role without changing the bits.
>
> Certainly not.  Most type casts actually change bits.

>From what I remember both in my own code and others that I have read,
most casts, where 'most' is measured in frequency of occurence in
actual code, which is what I meant by 'usually'. are pointer casts
where no bits are changed (at least on platforms I have had experience
with).  Your experience could be different.

>  For example,
> supposing floats and longs are both 32 bits, the expression
(float)1L
> will *not* return the floating point number with the same bit
pattern
> as 1L.  It returns 1.0.

My awareness of this possibility is one reason I added the qualifier
'at least usually'.  However, C's coercion rules make (in my
experience) explicit number casts rare in actual occurances.  Standard
C made them even rarer than in K&R C by adding autoconversion of
function arguments, so that, for instance, sqrt((double) 4) could
shrink to sqrt(4).

> Usually, the only casts that preserve the bit pattern are integer to
> pointer casts,

You left out pointer to pointer casts, which I believe are the most
common of all!

> and the C standard doesn't even guarantee that (unless
> C 2000 changed it).  In fact, the C standard says (or used to say)
> that 0 must always cast to a null pointer, even if the system
> represents integer 0 and null pointer with different bits, which
does
> (or used to) happen.

On which systems?  How widely used?  I also added 'at least usually'
to account for systems I don't know about ;-)

> IMO, a type cast is just a fancy name for an operator that takes an
> object and returns an object with the same "value" (whatever that
> means) but a different type.  In C, type casting happens to have a
> funny syntax.  In Python, it does not.  If someone asked, "does
Python
> have type casting?", I would say yes, except there's no special
syntax
> for it.  Rather, type casting is done by the calling type objects
> themselves.

In my opinion, it is unhelpful to refer to type-function calls as
casts.  To me, the baggage 'cast' carries is more confusing than
helpful.  For instance, a common conversion, between number and
string, cannot be done in C with a type cast but must also (as in
Python) be done with a function call.  Would you call C's atoi(),
atof(), and sprintf casts?  In C, the 'funny syntax' defines what I
believe most people call a type cast versus a function call.  This is
certainly true for both K&R and the Standard C committee.

Terry J. Reedy






More information about the Python-list mailing list