typesafe downward casting

Kai Henningsen Kai_Henningsen at ms.maus.de
Fri Apr 12 21:42:00 AEST 1991


DS>>I would maintain ... that a good program generally has few casts and a
DS>>good programming language allows most programs to be written without casts.
DS>
DS>Since C, and for the most part C++ as well, are not strongly typed languages
DS>and rely on casts to allow the programmer to make explicit changes in type,
DS>I would disagree with the above statement. Automatic or built in changes of
DS>type are essentially hidden rules which rely on the programmers intimate
DS>knowledge of the type structure and possibly even an intimate knowledge
DS>of the program  to understand what is really happening.

I think you got something backward there. C uses Casts for two completely
different purposes: one, to convert values (as in (double)1), something other
languages tend to do with explicut library calls (if it's not automatic the
same way as in C), and another, to make the compiler *interpret* the *same*
value different (as in (int *)"blabla").

While there is certainly use for the first variant, the second one is almost
always a sign of bad type design, sometimes by the programmer, sometimes by
the language designer.

In general, such a reinterpretation shouldn't be needed, neither automatic
nor explicit; the only exceptions I can think of in this moment are
* objects being assigned to parent classes (after all, they HAVE the needed
  properties)
* functions that have to manipulate "generic data", such as memory allocation
  or i/o base functions.

DS>of type checking the language provides. Erosion of that type checking
DS>provides more pitfalls into which programmers can fall.

Exactly - and Casts ARE such an erosion.

MfG Kai



More information about the Comp.lang.c mailing list