Language features and reinterpret casts

bearophile bearophileHUGS at lycos.com
Mon Sep 20 14:52:06 PDT 2010


On Reddit I have read some people complain that D2 is a too much complex language because it has too many features. Feature "count" increases a language complexity, but most of the complexity comes from other sources, like unwanted interactions between features, messy feature semantics, unspecified behaviour in corner cases, special cases, special cases of special cases, etc.

But tidy features able to solve a defined class of problems usually decrease the amount of work of the programmer.

Recently Bradley Mitchell in D.learn newsgroup has tried to implement the Quake fast inverse square root algorithm in D, and has found D lack the C++ reinterpret cast:
http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D.learn&article_id=21901

If you use the current dmd you are able to solve this problem using a union to reinterpret the bits. But:
- C Standard says that assigning to one member of a union and then accessing a different member is undefined behaviour.
- GCC is a practical compiler, so it has the -fno-strict-aliasing switch, that allows to use that trick. See "-Wstrict-aliasing" and:
http://stackoverflow.com/questions/2906365/gcc-strict-aliasing-and-casting-through-a-union
- Walter said that regarding such union semantics D acts as C. So that union trick will break with other future D compilers.

The need to perform a reinterpret cast is uncommon, I don't need it in Python, but it does happen in a system language.

So all this situation looks silly to me. A modern language as D can't force programmer to use undefined tricks to do something uncommon but licit. Adding a feature here increases language complexity a little, but removes troubles and makes coding simpler (no need to remember or invent tricks), safer (you are sure the compiler will act as you want), more explicit (because the person that reads the code doesn't need to reverse engineer the trick), more efficient (because if you have to use -fno-strict-aliasing it may reduce performance a little).

So unless you have a different solution, I think D is better with a reinterpret_cast(). An alternative solution is to put a standard reinterpretCast!(U)(x) into Phobos2, and then let people that implement future D compilers define its semantics correctly for that compiler. So the user code that uses this template is portable, safe, efficient, explicit in its purpose.

Bye,
bearophile


More information about the Digitalmars-d mailing list