Question: Is it possible to avoid casts entirely?
One minute response: What an interesting question. The answer is obviously yes in languages without types, such as most assembly languages. The answer is also yes, although perhaps arguably so, in dynamically-typed languages. As a practical matter, the answer is no for C++. For example, strings are useless without casts, because the only way I can specify string literals is to use character array literals and cast them to strings. (This is arguable, depending on whether or not you consider string s = string(10, 'a')
to be a cast. But, even if you win the argument, you lose because you're reduced to constructing strings by catenating individual string character literals.).
Question: Is it a bad idea to use casts if you are writing platform independent code in C++?
One minute response: You should always consider casts guilty until proven innocent. In some cases, casts can help maintain portability. For example, as mentioned in class, it is implementation dependent whether or not a character is a signed value. If you want to write a portable program that manipulates characters as other values, you should define your own character type to make sure the signedness doesn't change as your program moves from system to system. In other cases, casts can hinder portability. For example, as mentioned in class, the behavior of const casts is system dependent.
Overall, I suppose, casts can help improve portability: if you find yourself using casts, you should stop and think hard about how you can redesign your software to remove the casts. That can't but help improve portability.
This page last modified on 16 July 2003.