Nice way to cast a homogeneous tuple

Albert van der Horst albert at spenarnc.xs4all.nl
Sat Aug 7 09:54:28 EDT 2010


In article <1pm7i7-473.ln1 at satorlaser.homedns.org>,
Ulrich Eckhardt  <eckhardt at satorlaser.com> wrote:
>Steven D'Aprano wrote:
>> Perhaps I have been misinformed, but my understanding of C type-casts is
>> that (where possible), a cast like `int(var)` merely tells the compiler
>> to temporarily disregard the type of var and treat it as if it were an
>> int. In other words, it's a compiler instruction rather than a conversion
>> function.
>
>You are misinformed. The result of a cast in C or C++ behaves as if a
>temporary was created:
>
>  int x = 0;
>  unsigned(x)--; // invalid, compiler error
>
>Now, where this distinction gets blurred is when you are casting pointers:
>
>  (*(unsigned*)&x)--;
>
>or, in C++, references:
>
>  reinterpret_cast<unsigned&>(x)--;
>
>Technically, these are still invalid though, only that they give you
>undefined behaviour at runtime instead of a compiler error, but those are
>already very fine details of the according standards.

There is just one conclusion that should remain from this.
If you're ever going to program in in c or c++, casts are to be
avoided like the plague. (And recently they have been thought over in
C++ to be split in different names with the reinterpret_cast the most
dangerous, but at least it is a big read flag.)
I see an analogy with goto's in my experience. Once you understand
how bad they are, you discover there is always a better solution.

It is unfortunate that cast's in Python share the same name, but
it is kind of unavoidable because it is about the proper CS name to use.

>Uli

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst




More information about the Python-list mailing list